使用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. 最后附上代碼實現截圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM