Creating a folder if it does not exists - "Item already exists"

Powershell

Powershell 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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionlaitha0View Question on Stackoverflow
Solution 1 - Powershelllaitha0View Answer on Stackoverflow
Solution 2 - PowershellZomboView Answer on Stackoverflow
Solution 3 - PowershellWillem van KetwichView Answer on Stackoverflow