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

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

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

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

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

1 #access .NET Framework
2 [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
3 # config Computer Name
4 $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")
5 Rename-Computer -NewName $computer
6 # end of configure Computer Name

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

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

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

猜你喜欢

转载自www.cnblogs.com/springyun/p/9198470.html
今日推荐