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
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)