Frequently in PowerShell, we need to add a directory if it doesn’t already exist.
Simple Code – Check If the Directory Exists First
This assumes the higher level directories exist, and you just want to add the lowest level directory:
<pre>
$targetFilePath = "e:\Dropbox\Audios\Album\Sinatra"
if (!(Test-Path $targetFilePath))
{
New-Item -ItemType Directory -Path $targetFilePath | Out-Null
}
#
# Now you can write to that new directory, because you know it is there
#
</pre>
NOTES: If you don’t pipe it to Out-Null, then it will write a message to the console that you may not want.
<pre>
Directory: e:\Dropbox\Audios\Album\Sinatra
Mode LastWriteTime Length Name
---- ------------- ------ ----
da---- 5/30/2020 12:55 PM Sinatra
</pre>
ShortCut – Use the -Force parameter
This seems like a trick to me, but by specifying the -Force parameter.
The documentation on the -Force parameter says “Forces this cmdlet to create an item that writes over an existing read-only item. Implementation varies from provider to provider.”. The New-Item supports many different providers, one of which is the disk structure.
<pre>
$targetFilePath = "e:\Dropbox\Audios\Album\Sinatra"
New-Item -ItemType Directory -Path $targetFilePath -Force
#
# Now you can write to that new directory, because you know it is there
#
</pre>
Create the entire directory, with all parent paths
If you want to create the directory, including the DropBox folder, the Audios folder, and the Album folder, then the following function will do that. Just be careful, because if you misspell one of your higher level directories, it will create them rather than matching to the one you expected to match to.
<pre>
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
#or (to avoid the console output)
# New-Item -ItemType Directory -Path $global:foldPath | Out-Null
# Write-Host "$global:foldPath Folder Created Successfully"
}
}
}
#To Call The Above - note - do not use parentheses for the parameter to PowerShell functions
GenerateFolder "e:\Dropbox\Audios\Album\Sinatra"
#
# Now you can write to that new directory, because you know it is there
#
</pre>
GenerateFolder script from: Naredia Reddy on StackOverflow