You can do basic checking directly in the param using Read-Host but that just insures a value is provided.
param([string]$path = $(Read-Host -prompt "`tPath"))This will not guarantee that the data the script is expecting will be provided by the user nor can it provide confirmation that it is what the user meant. This can be very crucial when dealing with scripts that may delete or modify objects. Sometimes, you may even want to go the extra mile and ask, "Are you really sure?". The following code is a typical interrogation I would do when asking for a path to be supplied.
param([string]$path) if(![bool]$path) { Write-Host "You are missing the `"-path`" command line argument" -foregroundColor Red Write-Host "" Write-Host "This is the path that the script requires to perform its function." Write-Host "" while((![bool]$path)) { $path = Read-Host -prompt "`tPath" } Write-Host "" } if(!(Test-Path -path $path)) { Write-Host "Unable to locate: $path" -foregroundColor Red Write-Host "" Write-Host "Please review the correct path" Write-Host "" while(!(Test-Path -path $path)) { $path = Read-Host -prompt "`tPath" } Write-Host "" } $answer = $null while($answer -ne "Y" -and $answer -ne "N") { $answer = Read-Host -prompt "Are you sure you want to use $path (Y/N)?" } if($answer -eq "N") { Write-Host "" Write-Host "Quiting..." -foregroundColor Yellow exit } Write-Host "" Write-Host "`$path = $path"
No comments:
Post a Comment