Author Posts

March 10, 2017 at 6:53 pm

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
}

March 10, 2017 at 7:51 pm

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).

Using the System.Windows.Forms.FolderBrowserDialog Class

... and you can set a starting directory ...

March 11, 2017 at 5:53 am

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