【问题标题】:PowerShell Script Not Working as Expected (foreach loop)PowerShell 脚本未按预期工作(foreach 循环)
【发布时间】:2017-06-21 05:39:44
【问题描述】:

我正在使用下面的 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!!"
    }
}

【问题讨论】:

    标签: powershell foreach server


    【解决方案1】:

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

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

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

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

    像往常一样,MS 脚本专家也有一个WMI based solution

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 2020-12-05
        • 2022-06-17
        • 1970-01-01
        • 2016-09-07
        • 2018-10-19
        • 1970-01-01
        相关资源
        最近更新 更多