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

6

36

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
Adermin answered 8/11, 2013 at 7:2 Comment(0)
D
49

Add the -Force parameter to the command.

Dodd answered 8/11, 2013 at 7:5 Comment(3)
Is there any reason why -Force wouldn't work? In my OctopusDeploy script, this was generated. $tempfolder was a UNC path. screencast.com/t/iB5rlt4Ae1Santalaceous
Never mind ... it's because my OctopusDeploy script was running as SYSTEM, which has no rights to the UNC path in question.Santalaceous
I don't like '-Force' when using PowerShell 7, because when the folder already exists, adding '-Force' causes a listing of the folder to appear on the output of the command. Whereas, instead of using '-Force' you can use @peter-mortensen 's answer, which is to add '-ErrorAction SilentlyContinue'. This option causes no 'noisy' folder listing to appear on the output.Scram
C
31

Use:

mkdir C:\dog -ErrorAction SilentlyContinue
Coronal answered 8/11, 2013 at 7:31 Comment(2)
This ignores all errors. E.g. if you were not authorized to create the directory, you now have no directory created and your script continues. Ignoring only the error when the directory exists means there IS a dog directory when your script continues.Jasminejason
This is the BEST answer, in my opinion, because it does not cause a directory listing to appear on the output like the '-Force' argument.Scram
C
2

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"
}
Claudineclaudio answered 8/11, 2013 at 7:14 Comment(2)
Not reli agree, in linux mkdir -p , doesn't prompt error message even it exists.Adermin
In my opinion, that is WAY too much typing/effort required, when all you want is for the attempt to create the directory to be made, but WITHOUT complaining if it already exists.Scram
C
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!

Carleencarlen answered 15/3, 2016 at 5:16 Comment(1)
-Force is a parameter of New-Item, sorry that was very much the wrong terminology! Taking out the Write-Host in the above command does speed things up big time! Poor example, but the result is still similar. Sorry for the confusion guys!Carleencarlen
D
1

You can just use an if:

if (-not (test-path C:/dog)) { mkdir -p C:/dog }

-p creates all non-existing directories in the path.

The downside of this is, that you need to name your path twice.

Dori answered 9/6, 2023 at 10:2 Comment(0)
P
0

Powershell 7 ( || didn't work):

(test-path foo) ? $null : (mkdir foo)
Pickaxe answered 12/6, 2020 at 19:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.