PowerShell脚本无法按预期工作(foreach循环)

时间:2017-06-21 05:39:45

标签: powershell foreach server

我使用PowerShell脚本下方将服务器电源计划设置为高性能模式。问题是,即使在通过文本文件(Servers.txt)传递服务器名称之后,它也只对我执行脚本的服务器进行了更改。我已经使用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!!"
    }
}

2 个答案:

答案 0 :(得分:1)

问题在于虽然使用foreach循环来迭代所有服务器,但这些名称从不用于实际的电源配置。也就是说,

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

将始终在本地系统上执行。因此,远程服务器上没有更改电源计划。

作为一种解决办法,可能会psexec或Powershell远程处理,因为powercfg似乎不支持远程系统管理。

MS Scripting Guys也像往常一样WMI based solution

答案 1 :(得分:0)

从你的问题的要点,我想你可能想尝试在Invoke-Command 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!!"
    }

}

}