2017-06-21 86 views
1

我正在使用PowerShell腳本將服務器電源計劃設置爲高性能模式。問題是,即使在通過文本文件(Servers.txt)傳遞服務器名稱之後,它僅更改了正在執行腳本的服務器。我用foreach循環遍歷服務器列表,但仍然沒有運氣。不知道我錯在哪裏邏輯,有人可以幫助這個。提前致謝。PowerShell腳本按預期工作(foreach循環)

$file = get-content J:\PowerShell\PowerPlan\Servers.txt 
foreach ($args in $file) 
{ 
    write-host "`r`n`r`n`r`nSERVER: " $args 
    Try 
    { 
     gwmi -NS root\cimv2\power -Class win32_PowerPlan -CN $args | select ElementName, IsActive | ft -a 
     #Set power plan to High Performance 
     write-host "`r`n<<<<<Changin the power plan to High Performance mode>>>>>" 
     $HighPerf = powercfg -l | %{if($_.contains("High performance")) {$_.split()[3]}} 
     $CurrPlan = $(powercfg -getactivescheme).split()[3] 
     if ($CurrPlan -ne $HighPerf) {powercfg -setactive $HighPerf} 
     #Validate the change 
     gwmi -NS root\cimv2\power -Class win32_PowerPlan -CN $args | select ElementName, IsActive | ft -a 
    } 
    Catch 
    { 
      Write-Warning -Message "Can't set power plan to high performance, have a look!!" 
    } 
} 

回答

1

的問題是,雖然foreach循環用於遍歷所有的服務器,名字永遠不會用於實際的動力配置。即,

$HighPerf = powercfg -l | %{if($_.contains("High performance")) {$_.split()[3]}} 

將始終在本地系統上執行。因此,遠程服務器上沒有更改電源計劃。

作爲解決方法,或許psexec或Powershell遠程處理會這樣做,因爲powercfg似乎不支持遠程系統管理。

MS腳本專家同樣也有WMI based solution

+0

喜vonPryz通過系統的名稱,由於一噸,我已經糾正了它。 –

0

從你的問題的要點,我認爲你可能想嘗試運行命令的調用命令Invoke-Command Documentation一套完整和-ComputerName

$file = get-content J:\PowerShell\PowerPlan\Servers.txt 
foreach ($args in $file) 
{ 
invoke-command -computername $args -ScriptBlock { 
write-host "`r`n`r`n`r`nSERVER: " $args 
    Try 
    { 
     gwmi -NS root\cimv2\power -Class win32_PowerPlan -CN $args | select ElementName, IsActive | ft -a 
     #Set power plan to High Performance 
     write-host "`r`n<<<<<Changin the power plan to High Performance mode>>>>>" 
     $HighPerf = powercfg -l | %{if($_.contains("High performance")) {$_.split()[3]}} 
     $CurrPlan = $(powercfg -getactivescheme).split()[3] 
     if ($CurrPlan -ne $HighPerf) {powercfg -setactive $HighPerf} 
     #Validate the change 
     gwmi -NS root\cimv2\power -Class win32_PowerPlan -CN $args | select ElementName, IsActive | ft -a 
    } 
    Catch 
    { 
      Write-Warning -Message "Can't set power plan to high performance, have a look!!" 
    } 

} 

}