这个问题在这里已有答案:
我试图使用PowerShell创建一个文件夹,如果它不存在所以我做了:
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = "$DOCDIR\MatchedLog"
if(!(Test-Path -Path MatchedLog )){
New-Item -ItemType directory -Path $DOCDIR\MatchedLog
}
这给了我文件夹已经存在的错误,但它不应该尝试创建它。
我不确定这里有什么问题
New-Item:具有指定名称C:\ Users \ l \ Documents \ MatchedLog的项目已存在。在C:\ Users \ l \ Documents \ Powershell \ email.ps1:4 char:13 + New-Item <<<< -ItemType directory -Path $ DOCDIR \ MatchedLog + CategoryInfo:ResourceExists:(C:\ Users \ l。 ... ents \ MatchedLog:String)[New-Item],IOException + FullyQualifiedErrorId:DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand`
我甚至没有集中注意力,这里是如何做到的
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
使用New-Item,您可以添加Force参数
New-Item -Force -ItemType directory -Path foo
或者ErrorAction参数
New-Item -ErrorAction Ignore -ItemType directory -Path foo
使用-Not
运算符的替代语法,并取决于您对可读性的偏好:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}