Learning Powershell Loops

Tagged: 

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Curtis Smith Curtis Smith 2 weeks, 3 days ago.

  • Author
    Posts
  • #66141
    Profile photo of Jared
    Jared
    Participant

    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
    }
    
  • #66142
    Profile photo of Olaf Soyk
    Olaf Soyk
    Participant

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

  • #66159
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    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

You must be logged in to reply to this topic.