79

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`

wonea
  • 4,783
  • 17
  • 86
  • 139
laitha0
  • 4,148
  • 11
  • 33
  • 49

3 Answers3

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
}
laitha0
  • 4,148
  • 11
  • 33
  • 49
  • 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 '13 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 '14 at 21:19
63

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zombo
  • 1
  • 62
  • 391
  • 407
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
}
Willem van Ketwich
  • 5,666
  • 7
  • 49
  • 57
  • 1
    Alternatively, even simpler: if (-Not (Get-Item C:\Temp)) { New-Item -ItemType dir "C:\Temp" } Assuming you want to create C:\Temp. – shivesh suman Oct 01 '18 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' – Patrick Burwell Oct 13 '21 at 19:24