PowerShell:如果File AlReadys存在“ MKDIR”命令,该如何抑制错误?

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}

第一次运行(创建文件夹对象):5 ms

第二次运行(在文件夹存在之后):1 ms

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"}}

第一次运行(创建文件夹对象):54 ms

第二次运行(在文件夹存在之后):15 ms

谢谢彼得清理我的帖子!你是男人!

Powershell 7( || 不起作用):

(test-path foo) ? $null : (mkdir foo)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top