【问题标题】:Powershell To Create Folder If Not ExistsPowershell 如果不存在则创建文件夹
【发布时间】:2017-06-28 22:34:47
【问题描述】:

我正在尝试解析文件夹中的文件名并将部分文件名存储在变量中。查看!然后,我想获取其中一个变量并检查该文件夹名称是否存在于其他位置,以及是否没有创建它。如果我使用Write-Host,则文件夹名称是有效路径,并且文件夹名称不存在,但在执行脚本时,文件夹仍未创建。

如果文件夹不存在,我应该怎么做?

$fileDirectory = "C:\Test\"
$ParentDir = "C:\Completed\"
foreach ($file in Get-ChildItem $fileDirectory){

    $parts =$file.Name -split '\.'

    $ManagerName = $parts[0].Trim()
    $TwoDigitMonth = $parts[1].substring(0,3)
    $TwoDigitYear = $parts[1].substring(3,3)

    $FolderToCreate = Join-Path -Path $ParentDir -ChildPath $ManagerName

    If(!(Test-Path -path "$FolderToCreate\"))
    {
        #if it does not create it
        New-Item -ItemType -type Directory -Force -Path $FolderToCreate
    }

}

【问题讨论】:

  • 试试这个:New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
  • 如果文件夹存在,New-Item 不会创建它。所以问题真的是如何抑制错误,对吧?

标签: powershell create-directory


【解决方案1】:
if (!(Test-Path $FolderToCreate -PathType Container)) {
    New-Item -ItemType Directory -Force -Path $FolderToCreate
}

【讨论】:

  • 警告:该文件夹可能由 Test-Path 和 New-Item 之间的另一个进程创建。
  • 我推荐if (-not(Test-Path... 以获得更好的可读性。 ! 很难被发现。
【解决方案2】:

尝试使用 -Force 标志 - 当每个子目录不存在时,它会检查每个子目录,它会简单地创建它并转到下一个并且永远不会抛出错误。

在下面的示例中,您需要 7 个嵌套的子目录,一行您可以创建任何不存在的子目录。

您还可以根据需要多次重新运行它,它的设计目的是永远不会抛出错误!

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

【讨论】:

  • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of 如何解决这个问题。没有这个,你的回答就没有多少教育价值了——记住你是在为未来的读者回答这个问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
  • 赞成使用 Force 来创建整个树。
【解决方案3】:

其他解决方案:

if (![System.IO.Directory]::Exists($FolderToCreate ))
{
     New-Item -ItemType Directory -Force -Path $FolderToCreate
}

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 2011-01-19
    • 1970-01-01
    • 2018-02-10
    • 2016-06-26
    • 2014-09-07
    • 2013-09-18
    • 2011-02-19
    相关资源
    最近更新 更多