使用Powershell实现计算机名称及IP地址修改

时间:2022-06-26 17:21:34

我的第一篇博客分享,写这个代码的用途是在公司Ghost完系统之后去修改本地计算机名称及IP 地址,用Powershell实现。

1. 代码第一部分,检查Powershell是否已管理员权限执行,如果不是的话,强制以管理员权限开启一个powershell窗口.

 #region Key code: force to run with administrator rights
$currentWi = [Security.Principal.WindowsIdentity]::GetCurrent()
$currentWp = [Security.Principal.WindowsPrincipal]$currentWi if( -not $currentWp.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
$boundPara = ($MyInvocation.BoundParameters.Keys | foreach{
'-{0} {1}' -f $_ ,$MyInvocation.BoundParameters[$_]} ) -join ' '
$currentFile=(Resolve-Path $myInvocation.MyCommand.Source).Path $fullPara = $boundPara + ' ' + $args -join ' '
Start-Process "$psHome\powershell.exe" -ArgumentList "$currentFile $fullPara" -verb runas
return
}
#endregion

2. 第二部分,调用.NET Framework创建一个窗口输入新的computer name,之后重命名

 #access .NET Framework
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
# config Computer Name
$computer=[Microsoft.VisualBasic.Interaction]::InputBox("Please enter a computer name. Standard names can contain letters (a-z, a-z), Numbers (0-9), and hyphen (-).", "Computer Name", "$env:computername")
Rename-Computer -NewName $computer
# end of configure Computer Name

3. 第三部分, 因为ghost后的系统网络名称不是原来的Local Area Connection,而会变成Local Area Connection #2类似这样后边跟数字的名称,所以我们需要调用gwmi组件并且正则表达式去匹配并选定网络名称包含Local Area Connection 的adapter,然后再去set ip地址.

 # Configure the local network IP address
$IP=[Microsoft.VisualBasic.Interaction]::InputBox("Please enter the IP address, such as 192.168.1.1", "IP Address",'192.168.1.2')
$parttern="^Local Area Connection"
$NICs=gwmi win32_networkadapter `
| Where {$_.NetConnectionID -match $parttern}
foreach($NIC in $NICs) {
$N=$NIC.NetConnectionID
netsh interface ip set address name="$N" source=static addr=$IP
}
if($Error.Count -eq 0) {
echo "Set OK!!!!"
}
Write-Host 'Press any key to exit ...'
Read-Host
# end of configure the local network IP address

4. 最后附上代码实现截图:

使用Powershell实现计算机名称及IP地址修改