Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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`

like image 781
laitha0 Avatar asked Jun 26 '13 20:06

laitha0


2 Answers

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
}
like image 123
laitha0 Avatar answered Nov 02 '22 06:11

laitha0


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
like image 62
Zombo Avatar answered Nov 02 '22 07:11

Zombo