Powershell 创建文件夹,如果不存在

Powershell To Create Folder If Not Exists

我正在尝试解析文件夹中的文件名并将部分文件名存储在变量中。查看!然后我想获取其中一个变量并检查该文件夹名称是否存在于不同的位置,以及它是否不创建它。如果我使用 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
    }

}
if (!(Test-Path $FolderToCreate -PathType Container)) {
    New-Item -ItemType Directory -Force -Path $FolderToCreate
}

其他解决方案:

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

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

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

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

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