Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Try Catch and retry?

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

like image 283
IIIdefconIII Avatar asked Jun 11 '17 22:06

IIIdefconIII


People also ask

How do I retry a PowerShell command?

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.

What is PowerShell try catch?

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.

How do I throw an exception in PowerShell?

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.


1 Answers

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)
like image 166
colsw Avatar answered Sep 21 '22 03:09

colsw