PowerShell : "mkdir"명령에 파일 Alreadys가 존재하는 경우 오류를 어떻게 억제 할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/19853340

  •  29-07-2022
  •  | 
  •  

문제

고려하다:

PS Y:\> mkdir  C:/dog


    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         11/7/2013  10:59 PM            dog


PS Y:\> mkdir  C:/dog
New-Item : Item with specified name C:\dog already exists.
At line:38 char:24
+         $scriptCmd = {& <<<<  $wrappedCmd -Type Directory @PSBoundParameters }
    + CategoryInfo          : ResourceExists: (C:\dog:String) [New-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
도움이 되었습니까?

해결책

추가 -Force 명령에 매개 변수.

다른 팁

사용:

mkdir C:\dog -ErrorAction SilentlyContinue

오류 메시지를 억압하지 않는 것이 가장 좋습니다 (유효한 이유가없는 한). 디렉토리를 만들려고하는 대신 디렉토리가 존재하는지 확인하십시오. 그렇다면 내용을 제거하거나 다른 이름을 선택해야합니까? 그렇게 좋아,

if (-not (test-path "c:\foobar") ) {
    write-host "c:\foobar doesn't exist, creating it"
    md 'c:\foobar'|out-null
} else {
    write-host "c:\foobar exists, no need to create it"
}

오류를 억제하는 동안 일반적으로 당신이 말하는 것처럼 모범 사례가 아니라고 추가하고 싶었습니다. -Force 이전에 존재하는지 확인하는 것보다 훨씬 빠르게 실행됩니다.

여기서 d : 는 램 디스크입니다.

Measure-Command {new-item "D:\NewFolder\NewSubFolder" -ItemType Directory -force}

첫 번째 실행 (폴더 개체 생성) : 5ms

두 번째 실행 (폴더가 존재 한 후) : 1ms

Measure-Command {if (-not (test-path "D:\NewFolder\NewSubFolder") ) {
write-host "Directory doesnt exist, creating it"
md "D:\NewFolder\NewSubFolde"|out-null} else {
write-host "Directory exists, no need to create it"}}

첫 번째 실행 (폴더 개체 생성) : 54ms

두 번째 실행 (폴더가 존재 한 후) : 15ms

내 게시물을 정리해 주신 Peter에게 감사드립니다! 당신은 남자입니다!

PowerShell 7 ( || 작동하지 않았습니다) :

(test-path foo) ? $null : (mkdir foo)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top