Problem
How can I prevent the creation of folders with spaces in the name from within my script.
Solution
001
002 003 004 005 006 007 008 009 010 |
function New-Folder {
param ( [string]$path = "C:\Test", [string]$name = "" ) if($name.Indexof(" ") -ge 0){throw "Folder name contains spaces"} if (!(Test-Path -Path $path)){throw "Invalid path"} if ($name -eq ""){throw "Invalid folder name"} New-Item -Path $path -Name $name -ItemType directory } |
Define the path and new folder name to the function as parameters. Use the IndexOf method to check for spaces in the name and throw an exception if one is found. Just need a general check as one space is enough to stop the creation. While we are at it we will check that the path exists and that the name is not empty because
"".IndexOf(" ") returns –1 i.e. it doesn’t find any.
We can then use new-item to create the folder as normal