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.
Get-ChildItem
command - this is taking the path you enter and trying to enumerate the contents, and failing when the path is invalid. You only need theRead-Host
call:$path = Read-Host -Prompt "Please enter a path"
– boxdog