首页 文章

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

提问于
浏览
61

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

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

3 回答

  • 99

    我甚至没有专注,这里是如何做到的

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

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

    New-Item -Force -ItemType directory -Path foo
    

    或者ErrorAction参数

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

    使用 -Not 运算符的替代语法,并根据您的可读性偏好:

    if( -Not (Test-Path -Path $TARGETDIR ) )
    {
        New-Item -ItemType directory -Path $TARGETDIR
    }
    

相关问题