PowerShell: Test-Path -IsValid не работает - PullRequest
1 голос
/ 17 апреля 2020

Командлет PowerShell Test-Path :c\df -IsValid (и вариант Test-Path -IsValid :c\df) возвращает true для синтаксиса, который явно недопустим. Может кто-то пролить свет на это; я что-то пропустил?

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>

1 Ответ

0 голосов
/ 17 апреля 2020

Для примера, который я представил, решение является следующим:

try { mkdir :c\df } catch {write-output "Invalid Path"; exit}

Поскольку это входит в более крупный сценарий, я включил в условный оператор IF-THEN, например:

    # 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"
        }
    }
...