Powershell: How Can I Suppress the Error If File Alreadys Exists for "Mkdir" Command?

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

5 Answers

Add the -Force parameter to the command.

2

Use:

mkdir C:\dog -ErrorAction SilentlyContinue
1

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

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!

1

Powershell 7 ( || didn't work):

(test-path foo) ? $null : (mkdir foo)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest