ChatGPT解决这个技术问题 Extra ChatGPT

如果目录不存在则创建

如果它们不存在,我正在编写一个 PowerShell 脚本来创建几个目录。

文件系统看起来与此类似

D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\

每个项目文件夹都有多个修订版。

每个修订文件夹都需要一个 Reports 文件夹。

一些“修订”文件夹已经包含一个报告文件夹;但是,大多数都没有。

我需要编写一个每天运行的脚本来为每个目录创建这些文件夹。

我能够编写脚本来创建一个文件夹,但是创建多个文件夹是有问题的。

“创建多个文件夹是有问题的” - 你有什么样的问题?你不知道怎么写鳕鱼?您收到错误消息吗?脚本运行后文件夹不会出现吗?不同的问题需要不同的解决方案。

P
Peter Mortensen

试试 -Force 参数:

New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist

您可以先使用 Test-Path -PathType Container 进行检查。

有关详细信息,请参阅 New-Item MSDN 帮助文章。


对于懒惰的人,有一个简写: md -Force c:\foo\bar\baz
对于那些在创建文件夹时不想要任何输出的人,在末尾添加“| Out-Null”
-Force 实际上会做什么? The documentation“强制此 cmdlet 创建一个覆盖现有只读项目的项目”。它会删除现有文件夹吗?这个答案应该很清楚。
@PeterMortensen 在目录的情况下,强制它们不会清除现有内容,它只会抑制错误消息,指出它已经创建。此命令还将创建任何必要的干预文件夹,如果这些文件夹的内容已经存在,它们也是安全的。
警告:如果路径中有文件,这将静默进行,这与 [System.IO.Directory]::CreateDirectory('path') 不同
n
ndemou
$path = "C:\temp\NewFolder"
If(!(test-path -PathType container $path))
{
      New-Item -ItemType Directory -Path $path
}

Test-Path -PathType container 检查路径是否存在且是否为目录。如果没有,它将创建一个新目录。如果路径存在但是是文件,New-Item 将引发错误(如果有风险,可以使用 -force 参数覆盖文件)。


好的!如果目录已经存在(因为它使用 test-path),这会使输出静音。
为什么选择 -Force
@KCD 负责薛定谔的目录
r
rkyser
[System.IO.Directory]::CreateDirectory('full path to directory')

这在内部检查目录是否存在,如果没有目录,则创建一个。只需一行和本地 .NET 方法即可完美运行。


我可以对当前工作目录执行本地/相对路径吗?
@AaronFranke 你可以使用 [System.IO.Path]::Combine($PWD.Path, 'relativeDirectory')
S
Steve Taylor

利用:

$path = "C:\temp\"
    
If (!(test-path $path))
{
    md $path
}

第一行创建一个名为 $path 的变量,并为其分配字符串值“C:\temp”

第二行是一个 If 语句,它依赖于 Test-Path cmdlet 来检查变量 $path 是否不存在。不存在使用 !象征。

第三行:如果没有找到上面字符串中存储的路径,则运行大括号之间的代码。

md 是输入的简短版本:New-Item -ItemType Directory -Path $path

注意:如果路径已经存在,我还没有测试使用 -Force 参数来查看是否存在不良行为。

New-Item -ItemType Directory -Path $path

这也适用于目录层次结构 md "C:\first\second\third 全部创建。
在上面,如果第三个不存在,我如何创建一个名为“第三个”的文件夹
P
Peter Mortensen

以下代码片段可帮助您创建完整路径。

Function GenerateFolder($path) {
    $global:foldPath = $null
    foreach($foldername in $path.split("\")) {
        $global:foldPath += ($foldername+"\")
        if (!(Test-Path $global:foldPath)){
            New-Item -ItemType Directory -Path $global:foldPath
            # Write-Host "$global:foldPath Folder Created Successfully"
        }
    }
}

上面的函数分割你传递给函数的路径,并检查每个文件夹是否存在。如果它不存在,它将创建相应的文件夹,直到创建目标/最终文件夹。

要调用该函数,请使用以下语句:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"

这不是最简单的,但很容易理解。
假设,如果我有一个路径“\\shared1\folder1\”并且我想在这个路径中创建一个 LOGS 文件夹,如果它不存在,我该如何编码?因为 \\shared1\folder1\ 是一个变量,而不是硬编码的。我的意思是,如果 \\shared1\folder1\LOGS 不存在,则必须创建它。
P
Peter Mortensen

我有同样的问题。你可以使用这样的东西:

$local = Get-Location;
$final_local = "C:\Processing";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        mkdir $final_local;
        cd $final_local;
        liga;
    }

    ## If path already exists
    ## DB Connect
    elseif ((Test-Path $final_local) -eq 1)
    {
        cd $final_local;
        echo $final_local;
        liga;  (function created by you TODO something)
    }
}

P
Peter Mortensen

当您指定 -Force 标志时,如果文件夹已存在,PowerShell 将不会抱怨。

单线:

Get-ChildItem D:\TopDirec\SubDirec\Project* | `
  %{ Get-ChildItem $_.FullName -Filter Revision* } | `
  %{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }

顺便说一句,要安排任务,请查看此链接:Scheduling Background Jobs


P
Peter Mortensen

我知道使用 PowerShell 创建目录的三种方法:

Method 1: PS C:\> New-Item -ItemType Directory -path "C:\livingston"

https://i.stack.imgur.com/rtvCV.jpg

Method 2: PS C:\> [system.io.directory]::CreateDirectory("C:\livingston")

https://i.stack.imgur.com/a2TA2.jpg

Method 3: PS C:\> md "C:\livingston"

https://i.stack.imgur.com/tBN1V.jpg


请注意,`md` 只是 `mkdir`(制作目录)的 Powershell 默认别名,这是一个类似于 Linux/Unix mkdir 的 windows 命令。参考:`获取别名md`
P
Peter Mortensen

从您的情况来看,您需要每天创建一个“Revision#”文件夹,其中包含“Reports”文件夹。如果是这种情况,您只需要知道下一个修订号是什么。编写一个获取下一个修订号的函数 Get-NextRevisionNumber。或者你可以做这样的事情:

foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
    # Select all the Revision folders from the project folder.
    $Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory

    # The next revision number is just going to be one more than the highest number.
    # You need to cast the string in the first pipeline to an int so Sort-Object works.
    # If you sort it descending the first number will be the biggest so you select that one.
    # Once you have the highest revision number you just add one to it.
    $NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1

    # Now in this we kill two birds with one stone.
    # It will create the "Reports" folder but it also creates "Revision#" folder too.
    New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory

    # Move on to the next project folder.
    # This untested example loop requires PowerShell version 3.0.
}

PowerShell 3.0 installation


S
Styx

这是一个对我有用的简单方法。它检查路径是否存在,如果不存在,它不仅会创建根路径,还会创建所有子目录:

$rptpath = "C:\temp\reports\exchange"

if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}

P
Peter Mortensen

我希望能够轻松地让用户为 PowerShell 创建一个默认配置文件以覆盖某些设置,并最终得到以下单行语句(多个语句是的,但可以粘贴到 PowerShell 中并立即执行,这是主要目标):

cls; [string]$filePath = $profile; [string]$fileContents = '<our standard settings>'; if(!(Test-Path $filePath)){md -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; $fileContents | sc $filePath; Write-Host 'File created!'; } else { Write-Warning 'File already exists!' };

为了便于阅读,下面是我在 .ps1 文件中的做法:

cls; # Clear console to better notice the results
[string]$filePath = $profile; # Declared as string, to allow the use of texts without plings and still not fail.
[string]$fileContents = '<our standard settings>'; # Statements can now be written on individual lines, instead of semicolon separated.
if(!(Test-Path $filePath)) {
  New-Item -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; # Ignore output of creating directory
  $fileContents | Set-Content $filePath; # Creates a new file with the input
  Write-Host 'File created!';
}
else {
  Write-Warning "File already exists! To remove the file, run the command: Remove-Item $filePath";
};

J
John Bentley
$mWarningColor = 'Red'

<#
.SYNOPSIS
    Creates a new directory. 
.DESCRIPTION
    Creates a new directory. If the directory already exists, the directory will
    not be overwritten. Instead a warning message that the directory already
    exists will be output.
.OUTPUT
    If the directory already exists, the directory will not be overwritten.
    Instead a warning message that the directory already exists will be output.
.EXAMPLE    
    Sal-New-Directory -DirectoryPath '.\output'
#>
function Sal-New-Directory {
    param(
        [parameter(mandatory=$true)]
        [String]
        $DirectoryPath
    )
    $ErrorActionPreference = "Stop"
    try {
        if (!(Test-Path -Path $DirectoryPath -PathType Container)) {

            # Sal-New-Directory is not designed to take multiple 
            # directories. However, we use foreach to supress the native output
            # and substitute with a custom message.
            New-Item -Path $DirectoryPath -ItemType Container | `
              foreach {'Created ' + $_.FullName}
        } else {
            Write-Host "$DirectoryPath already exists and" `
                        "so will not be (re)created." `
                        -ForegroundColor $mWarningColor
        }
    } finally {
        $ErrorActionPreference = "Continue"
    }
}

“Sal”只是我自己的库的任意前缀。您可以将其删除或替换为您自己的。

另一个例子(放在这里是因为它会破坏stackoverflow语法高亮):

Sal-New-Directory -DirectoryPath ($mCARootDir + "private\")