PowerShell cmdlet Test-Path :c\df -IsValid
(and the variation Test-Path -IsValid :c\df
) is returning true
for syntax that is clearly not valid. Can someone shed light on this; am I missing something?
PS D:\GitHub\PowerShell_Scripts> Test-Path :c\df -IsValid
True
PS D:\GitHub\PowerShell_Scripts> Test-Path -IsValid :c\df
True
PS D:\GitHub\PowerShell_Scripts> mkdir :c\df
New-Item: The filename, directory name, or volume label syntax is incorrect. :
'D:\GitHub\PowerShell_Scripts\:c\df'
New-Item: The filename, directory name, or volume label syntax is incorrect. :
'D:\GitHub\PowerShell_Scripts\:c\df'
PS D:\GitHub\PowerShell_Scripts>
For the purpose of the example I provided, the following is a solution:
try { mkdir :c\df } catch {write-output "Invalid Path"; exit}
As this goes into a larger script, I included in an IF-THEN conditional statement like:
# Check whether ":c\df" (which is a variable in my script) exists.
# If it doesn't exist, TRY-CATCH by creating/deleting folder
$path=":c\df"
if (!(Test-Path -Path "$path"))
{
try
{
# Depending on command, user may want -ErrorAction as a switch
New-Item -ItemType "directory" -Path "$path" [-ErrorAction Stop]
# If ":c\df" had been correct, "c:\df", it would have created the folder.
# Remove new folder (if only interested in testing mkdir of $path)
Remove-Item -Path "$path"
}
catch
{
# For my purposes, I will run additional commands/logic to create
# a script generated unique folder to work with so my script can
# continue to function. The user can change it when finished.
# Alternatively, the script could inform the user of an error and exit
<commands to create new unique folder, $newFolder>
$path=".\$newFolder"
}
}