【发布时间】: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