I am new to power shell. I am trying to use the function like the goto in batch files.
In my script where I have$input1 = Read-Host "Please select an option 1, 2, 3. "
I want to Clear-Host and restart script if the use does not enter 1, 2, 3.
Write-Host 1. Convert Byte to Megabyte.
Write-Host
Write-Host 2. Convert Byte to Gigabyte.
Write-Host
Write-Host 3. Conver Byte to Terabyte.
#
#
# Assign value to the variables
#
$b2MB = '1048576'
$b2GB = '1073741824'
$b2TB = '1099511627776'
$input1 = ""
#
#
# prompts user for input from the main screen.
#
$input1 = Read-Host "Please select an option 1, 2, 3. "
#
#
# Depending on what the user input will execute a certain conversion.
#
#
if ( $input1 -eq 1 ) {
$mb2 = Read-Host " Enter how many bytes you want to convert to Megabytes? "
$bytesToMb = $mb2 / $b2MB
Write-Host $mb2 'is equal to '$bytesToMb' Megabytes'
} elseif ($input1 -eq 2) {
$mb3 = Read-Host " Enter how many bytes you want to convert to Gigabytes? "
$bytesToGb = $mb3 / $b2GB
Write-Host $mb3 'is equal to '$bytesToGb' Gigabytes'
} elseif ( $input1 -eq 3) {
$mb4 = Read-Host " Enter how many bytes you want to convert to Terabytes? "
$bytesToTb = $mb4 / $b2TB
Write-Host $mb4 'is equal to '$bytesToTb' Terabytes'
} else {
Write-Host " You have entered an invalid option. "
}
I believe you want something like this:
# Start a continuous loop
while ($true) {
# Write messages
Write-Host 1. Convert Byte to Megabyte.
Write-Host
Write-Host 2. Convert Byte to Gigabyte.
Write-Host
Write-Host 3. Conver Byte to Terabyte.
# Get the input
$input1 = Read-Host "Please select an option 1, 2, 3. "
# See if the input equals 1, 2, or 3. If so, break the loop.
if (1..3 -contains $input1) { break }
# If we get here, then the input was bad.
# So, we clear the host and let the loop start-over
Clear-Host
}
#
#
# Assign value to the variables
#
$b2MB = '1048576'
$b2GB = '1073741824'
$b2TB = '1099511627776'
#
#
# Depending on what the user input will execute a certain conversion.
#
#
if ( $input1 -eq 1) {
$mb2 = Read-Host " Enter how many bytes you want to convert to Megabytes? "
$bytesToMb = $mb2 / $b2MB
Write-Host $mb2 'is equal to '$bytesToMb' Megabytes'
} elseif ($input1 -eq 2) {
$mb3 = Read-Host " Enter how many bytes you want to convert to Gigabytes? "
$bytesToGb = $mb3 / $b2GB
Write-Host $mb3 'is equal to '$bytesToGb' Gigabytes'
} elseif ( $input1 -eq 3) {
$mb4 = Read-Host " Enter how many bytes you want to convert to Terabytes? "
$bytesToTb = $mb4 / $b2TB
Write-Host $mb4 'is equal to '$bytesToTb' Terabytes'
} else {
Write-Host " You have entered an invalid option. "
}