PowerShell: How can I suppress the error if file alreadys exists for "mkdir" command?

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

  •  29-07-2022
  •  | 
  •  

Question

Consider:

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
Was it helpful?

Solution

Add the -Force parameter to the command.

OTHER TIPS

Use:

mkdir C:\dog -ErrorAction SilentlyContinue

It is a best practice to not supress error messages (unless you have a valid reason). Check if the directory exists instead of just trying to create one. If it does, maybe you need to remove its contents or pick another a name? Like so,

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

I just wanted to add that while suppressing the error is usually not best practice as you say, the command -Force runs much faster than checking if it exists prior.

Where D:\ is a RAM disk:

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

First run (creating folder object): 5 ms

Second run (after folder exists): 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"}}

First run (creating folder object): 54 ms

Second run (after folder exists): 15 ms

Thank you Peter for cleaning up my post! You are the man!

Powershell 7 ( || didn't work):

(test-path foo) ? $null : (mkdir foo)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top