Hello, I’m learning Powershell and how to create basic loops.
My goal is to simplify a loop that I’ve created which forces a user to enter a valid path. My current loop works but it seems like there might be a better way to do it?
Thanks for your help!
$migratefrom = Read-Host -Prompt "Please enter the current data location in UNC format - e.x. "
$validpath = Test-Path $migratefrom
if ($validpath -like "true")
{
Write-Host "Path is good...procceding" -ForegroundColor DarkRed -BackgroundColor yellow
}
else
{
do{
$migratefrom = Read-Host -Prompt "TRY AGAIN: Please enter the current data location in UNC format - e.x. "
$validpath = Test-Path $migratefrom
}
until ($validpath -like "true")
Write-Host "You finally got it right. Path is good...procceding" -ForegroundColor DarkRed -BackgroundColor yellow
}
A slightly reliable way to ask someone for a folder path or a file path is to use a standard windows select folder dialog (or select file or select files).
Well, the simplest form of your loop would be this
Do {
$path = Read-Host -Prompt "Please enter the current data location in UNC format - e.x. "
} Until (Test-Path $path)
Here is another way to do it keeping the retry prompts and the end result is an object with the path info.
Do {
If(-Not (Get-Item (Read-Host -Prompt "Please enter the current data location in UNC format - e.x. ") -OutVariable path -ErrorAction SilentlyContinue)) {
Write-Host "Error retrieving path, try again" -ForegroundColor DarkRed -BackgroundColor yellow
}
} Until ($path)
Write-Host "Path found" -ForegroundColor DarkGreen -BackgroundColor White
$path