80

I am trying to create a folder using PowerShell if it does not exists so I did :

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = "$DOCDIR\MatchedLog"
if(!(Test-Path -Path MatchedLog )){
   New-Item -ItemType directory -Path $DOCDIR\MatchedLog
}

This is giving me error that the folder already exists, which it does but It shouldn't be trying to create it.

I am not sure what's wrong here

New-Item : Item with specified name C:\Users\l\Documents\MatchedLog already exists. At C:\Users\l\Documents\Powershell\email.ps1:4 char:13 + New-Item <<<< -ItemType directory -Path $DOCDIR\MatchedLog + CategoryInfo : ResourceExists: (C:\Users\l....ents\MatchedLog:String) [New-Item], IOException + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand`

1
  • try this:New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
    – Farzad J
    Apr 27, 2017 at 13:47

3 Answers 3

122

I was not even concentrating, here is how to do it

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}
2
  • 13
    The value of $TARGETDIR should be in double quotes, string expansion is disabled inside single and you'll end up with invalid path
    – Shay Levy
    Jun 26, 2013 at 20:40
  • 5
    Wouldn't an existing file of the same name as the folder you are trying to create match Test-Path -Path $TARGETDIR too? (Thinking of adding "-pathType container")
    – ftexperts
    Sep 10, 2014 at 21:19
64

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo
3
  • 1
    JFI "-ErrorAction Ignore" not supported in PowerShell 2
    – KindDragon
    Oct 20, 2015 at 17:22
  • 2
    An answer to a different question. Apr 1, 2016 at 15:24
  • 1
    To create the item without console printout: New-Item -Force -ItemType directory -Path D:\yourpath\1 | Out-Null
    – George
    Nov 15, 2016 at 2:33
21

Alternative syntax using the -Not operator and depending on your preference for readability:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}
2
  • 1
    Alternatively, even simpler: if (-Not (Get-Item C:\Temp)) { New-Item -ItemType dir "C:\Temp" } Assuming you want to create C:\Temp. Oct 1, 2018 at 23:10
  • '(if((test-path \\$ServersList\d$\install\foldertocopy -eq $false) { New-Item -force -ErrorAction Ignore -ItemType directory -Path \\$ServersList\d$\install\foldertocopy)|out-null' Oct 13, 2021 at 19:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.