Reputation: 363
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
Upvotes: 5
Views: 16562
Reputation: 363
Very satisfied with the end result, much thanks
#Change hostname
Write-Host "Change hostname " -NoNewLine
do{
$Failed = $false
Try{
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname')
Rename-Computer -NewName $ComputerName -ErrorAction Stop
Write-Host "- DONE -" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline
Write-Host "Hostname = $ComputerName" -ForegroundColor DarkGreen -BackgroundColor yellow
} catch { $Failed = $true }
} while ($Failed)
#Change workgroupname
Write-Host "Change Workgroup " -NoNewLine
do{
$Failed = $false
Try{
$WorkGroup = [Microsoft.VisualBasic.Interaction]::InputBox("Insert the Workgroupname:", 'Change WorkGroupName', 'werkgroep')
Add-Computer -WorkGroupName $WorkGroup -ErrorAction Stop
Write-Host "- DONE -" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline
Write-Host "Workgroup = $WorkGroup" -ForegroundColor DarkGreen -BackgroundColor yellow
} catch { $Failed = $true }
} while ($Failed)
Upvotes: 1
Reputation: 3326
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)
Upvotes: 12