I have this script
#Change hostname
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
Write-Host "Change hostname " -NoNewLine
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname')
Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline
Write-Host " hostname = $ComputerName "
Rename-Computer -NewName $ComputerName
when the computer name gets spaces, it fails cause a hostname cant have spaces. Can i block the form to have any spaces or does anyone knows how to get back to the inputbox when a error has been created for a re-try
Solution with passing a delegate into a function instead of script block: function Retry([Action]$action) { $attempts=3 $sleepInSeconds=5 do { try { $action. Invoke(); break; } catch [Exception] { Write-Host $_. Exception.
Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.
To create our own exception event, we throw an exception with the throw keyword. This creates a runtime exception that is a terminating error. It's handled by a catch in a calling function or exits the script with a message like this.
do {
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:','Change hostname')
} while ($ComputerName -match "\s")
using a do{}while()
loop and checking the Input doesn't have any whitespace should resolve your issue, this will re-prompt until a valid hostname is input, if you want to check for any errors at all:
do{
$Failed = $false
Try{
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname')
Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline
Write-Host " hostname = $ComputerName "
Rename-Computer -NewName $ComputerName -ErrorAction Stop
} catch { $Failed = $true }
} while ($Failed)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With