创建文件夹(如果该文件夹不存在) - “项目已存在”[复制]

问题描述 投票:65回答:3

这个问题在这里已有答案:

我试图使用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`

powershell
3个回答
105
投票

我甚至没有集中注意力,这里是如何做到的

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

48
投票

使用New-Item,您可以添加Force参数

New-Item -Force -ItemType directory -Path foo

或者ErrorAction参数

New-Item -ErrorAction Ignore -ItemType directory -Path foo

15
投票

使用-Not运算符的替代语法,并取决于您对可读性的偏好:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}
© www.soinside.com 2019 - 2024. All rights reserved.