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`
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With