Create directory if it does not exist
Solution 1:
Try the -Force
parameter:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
You can use Test-Path -PathType Container
to check first.
See the New-Item MSDN help article for more details.
Solution 2:
$path = "C:\temp\NewFolder"
If(!(test-path $path))
{
New-Item -ItemType Directory -Force -Path $path
}
Test-Path
checks to see if the path exists. When it does not, it will create a new directory.
Solution 3:
[System.IO.Directory]::CreateDirectory('full path to directory')
This internally checks for directory existence, and creates one, if there is no directory. Just one line and native .NET method working perfectly.
Solution 4:
The following code snippet helps you to create a complete path.
Function GenerateFolder($path) {
$global:foldPath = $null
foreach($foldername in $path.split("\")) {
$global:foldPath += ($foldername+"\")
if (!(Test-Path $global:foldPath)){
New-Item -ItemType Directory -Path $global:foldPath
# Write-Host "$global:foldPath Folder Created Successfully"
}
}
}
The above function split the path you passed to the function and will check each folder whether it exists or not. If it does not exist it will create the respective folder until the target/final folder created.
To call the function, use below statement:
GenerateFolder "H:\Desktop\Nithesh\SrcFolder"
Solution 5:
Use:
$path = "C:\temp\"
If (!(test-path $path))
{
md $path
}
-
The first line creates a variable named
$path
and assigns it the string value of "C:\temp" -
The second line is an
If
statement which relies on the Test-Path cmdlet to check if the variable$path
does not exist. The not exists is qualified using the!
symbol. -
Third line: If the path stored in the string above is not found, the code between the curly brackets will be run.
md
is the short version of typing out: New-Item -ItemType Directory -Path $path
Note: I have not tested using the -Force
parameter with the below to see if there is undesirable behavior if the path already exists.
New-Item -ItemType Directory -Path $path