III*_*III 3 powershell loops finally try-catch
我有这个脚本
#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
Run Code Online (Sandbox Code Playgroud)
当计算机名称获取空格时,它会失败导致主机名不能有空格.我可以阻止表单有任何空格,或者有人知道如何在重新创建错误时返回到输入框
do {
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:','Change hostname')
} while ($ComputerName -match "\s")
Run Code Online (Sandbox Code Playgroud)
使用do{}while()
循环并检查输入没有任何空格应解决您的问题,如果要检查任何错误,这将重新提示输入有效的主机名:
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)
Run Code Online (Sandbox Code Playgroud)
对最终结果非常满意,非常感谢
#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)
Run Code Online (Sandbox Code Playgroud)