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



我正在使用下面的PowerShell脚本将服务器电源计划设置为高性能模式。问题是,它只对我正在执行脚本的服务器进行更改,即使在通过文本文件(服务器.txt(传递服务器名称后也是如此。我已经使用foreach循环遍历服务器列表,但仍然没有运气。不确定我在哪里缺少逻辑,有人可以帮助解决这个问题。提前谢谢。

$file = get-content J:PowerShellPowerPlanServers.txt
foreach ( $args in $file)
{
    write-host "`r`n`r`n`r`nSERVER: " $args
    Try
    {
        gwmi -NS rootcimv2power -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 rootcimv2power -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!!"
    }
}

问题是,尽管使用foreach循环来迭代所有服务器,但这些名称从未用于实际的电源配置。那是

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

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

作为一种解决方法,也许psexec或Powershell远程处理就可以了,因为powercfg似乎不支持远程系统管理。

像往常一样,MS 脚本专家也有基于 WMI 的解决方案。

从您问题的要点来看,我认为您可能想尝试在调用命令调用命令文档中运行完整的命令集,并在 -ComputerName 中传递系统名称

$file = get-content J:PowerShellPowerPlanServers.txt
foreach ( $args in $file)
{
invoke-command -computername $args -ScriptBlock {
write-host "`r`n`r`n`r`nSERVER: " $args
    Try
    {
        gwmi -NS rootcimv2power -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 rootcimv2power -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!!"
    }
}
}

最新更新