Creating a folder if it does not exists - "Item already exists"
PowershellPowershell Problem Overview
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`
Powershell Solutions
Solution 1 - Powershell
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
}
Solution 2 - Powershell
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
Solution 3 - Powershell
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
}