#requires -Version 5.1 <# Normalize hostname by replacing underscore (_) with hyphen (-). Only applies Rename-Computer when an underscore exists. Requirements: - Run as Administrator. Notes: - Computer name change takes effect after restart. #> [CmdletBinding(SupportsShouldProcess = $true)] param( [switch]$Restart ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' function Test-IsAdministrator { try { $currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($currentIdentity) return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch { return $false } } if (-not (Test-IsAdministrator)) { throw 'Please run this script as Administrator.' } $currentName = $env:COMPUTERNAME if ([string]::IsNullOrWhiteSpace($currentName)) { throw 'Could not read current hostname.' } $newName = $currentName.Replace('_', '-') Write-Host ("Current hostname: {0}" -f $currentName) Write-Host ("Normalized hostname: {0}" -f $newName) if ($currentName -eq $newName) { Write-Host 'No underscore found. No change is required.' -ForegroundColor Yellow exit 0 } # Check NetBIOS computer name length limit. if ($newName.Length -gt 15) { throw ("Normalized hostname exceeds 15 characters: {0}" -f $newName) } if ($PSCmdlet.ShouldProcess($currentName, "Rename-Computer to $newName")) { Rename-Computer -NewName $newName -Force Write-Host 'Hostname changed. It will take effect after restart.' -ForegroundColor Green if ($Restart) { Write-Host 'Restarting now.' -ForegroundColor Yellow Restart-Computer -Force } else { Write-Host 'Please restart manually when ready.' -ForegroundColor Yellow } }