0

我正在编写一个 PowerShell 脚本来显示可用空间和 CPU 的状态,下面是代码段:

function Get_FreeSpace ($authType, $comp) {
    $freespace = Invoke-Command -ScriptBlock {
        Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='E:'" |
            Select-Object Size,Freespace
    } -ComputerName $comp -Credential $authType
    $freesize = [String]::Format("{0:P2}" -f ($freespace.Freespace / $freespace.Size))
    return $freesize
}

function Get_CPUAverage ($authType, $comp) {
    $Cpu_Average = Invoke-Command -ScriptBlock {
        Get-WmiObject Win32_Processor |
            Measure-Object -Property LoadPercentage -Average |
            Select-Object Average
    } -ComputerName $comp -Credential $authType
    return $Cpu_Average.Average
}

workflow Test-Workflow {
    foreach -parallel ($serv1 in $Servers) {
        $Size    = Get_FreeSpace -authType $cred -comp $serv1
        $Cpu_Avg = Get_CPUAverage -authType $cred -comp $serv1
        Write-Host $Size
    }
}

Test-Workflow

Write-Host $Size

$Size如果我使用-parallel循环,则不会返回任何内容。

4

2 回答 2

0

应该将 $Servers 作为参数传递,如下所示:

 workflow Test-Workflow {
   param($Servers)
   foreach -parallel ($serv1 in $Servers) {
      $Size    = Get_FreeSpace -authType $cred -comp $serv1
      $Cpu_Avg = Get_CPUAverage -authType $cred -comp $serv1
      Write-Host $Size
   }
 }

测试工作流 $Servers

于 2020-01-23T13:20:35.417 回答
0

或者,invoke-command 与多台计算机并行运行:

invoke-command comp1,comp2,comp3 { sleep 5; "done $env:computername" } 
于 2020-01-23T15:55:14.213 回答