Search code examples
powershellprompt

Best way to Stop a PowerShell Script or to re-ask the Right-Host


Here is my code. It feels really dirty and I have I have a long list of Right-Host Questions I'll be asking.

I'm wanting to stop the script if a Null, Blank, or otherwise empty (including just adding a space) entry is added. Right now I've got it to stop, but was hoping there was a cleaner way to group the "If" statements and perhaps to re-ask the question if any of the aforementioned entries happen...

$Parent = Read-Host -prompt "Enter full parent path that will contain the new folder"
if ( $Parent -eq $null)
  {
    Write-Host "You entered a blank value: This Script is now Exiting."
    Exit
  }
if ( $Parent -eq "")
  {
    Write-Host "You entered a blank value: This Script is now Exiting."
    Exit
  }
if ( $Parent -eq " ")
  {
    Write-Host "You entered a blank value: This Script is now Exiting."
    Exit
  }
else 
  {
    Write-Host "You Entered $Parent"
  }

$Name = Read-Host -prompt "Enter Folder Name"
if ( $Name -eq $null)
  {
    Write-Host "You entered a blank value: This Script is now Exiting."
    Exit
  }
if ( $Name -eq "")
  {
    Write-Host "You entered a blank value: This Script is now Exiting."
    Exit
  }
if ( $Name -eq " ")
  {
    Write-Host "You entered a blank value: This Script is now Exiting."
    Exit
  }
else 
  {
    Write-Host "You Entered $Name"
  }

Solution

  • You can put validation conditions together like that :

    $Parent = Read-Host -prompt "Enter full parent path that will contain the new folder"
    
     if ( ($Parent -eq $null) -or ($Parent -eq "") -or ($Parent -eq " "))
      {
    Write-Host "You entered a blank value: This Script is now Exiting."
      }
    else 
      {
    Write-Host "You Entered $Parent"
      }
    

    You can either make that a function with a mandatory non null parameter(as bill said much better/easier on the long run), or make a while loop until the input is right.