Peony
Peony

Reputation: 35

Validate an user input (path)

My problem is: a user should be able to input a path. If the input is not valid, it should repeat the process until the user inputs a valid path.

I tried to validate with Test-Path but I don't know what I am doing wrong.

My current code looks like this:

$repeatpath = $false
do {
    $path = Get-ChildItem -Path (Read-Host -Prompt "Please enter a path")
    if (Test-Path -Path $path -IsValid) {
        $repeatpath = $false
    } else {
        $repeatpath = $true
        "wrong path"
    }
} until ($repeatpath -eq $false) 

I get this error:

Get-ChildItem : Cannot find path 'C:\Hans' because it does not exist.
At C:\Users\Asli\Desktop\O2P2_Version1_2.ps1:146 char:17
+ ...     $path = Get-ChildItem -Path (Read-Host -Prompt "Please enter a pa ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Hans:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\Asli\Desktop\O2P2_Version1_2.ps1:147 char:29
+         if (Test-Path -Path $path -IsValid)
+                             ~~~~~
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand

I know that the path doesn't exist, that's good. But he should just echo "Wrong path" and repeat the process.

Upvotes: 1

Views: 1077

Answers (1)

Theo
Theo

Reputation: 61253

You could do without the need for the $repeatpath variable alltogether by using an endless While($true) loop.

This version uses the -IsValid switch to test the syntax of the path, regardless of whether the elements of the path exist. It returns $True if the path syntax is valid and $False if it is not.

while ($true) {
    $path = Read-Host -Prompt "Please enter a path"
    if (Test-Path -Path $path -IsValid) { break }

    Write-Host "Wrong path. Please try again" -ForegroundColor Red
}

Write-Host "Valid path: '$path'" -ForegroundColor Green

This version tests if the entered path exists or not.

while ($true) {
    $path = Read-Host -Prompt "Please enter a path"
    if (Test-Path -Path $path) { break }

    Write-Host "Wrong path. Please try again" -ForegroundColor Red
}

Write-Host "Valid path: '$path'" -ForegroundColor Green

Upvotes: 3

Related Questions