Tee-Object文件中的空白文件Powershell

时间:2017-01-31 18:17:15

标签: powershell output

为什么当我TEE-Object输出这个脚本时,我得到一个空白文件,我在屏幕上看到输出?

$Computers = (gc C:\Scripts\Computers.txt)

foreach ($Computer in $Computers) 
{
$Computer
Invoke-Command -ComputerName $Computer -ScriptBlock { winmgmt -standalonehost }

Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "UALSVC" -ErrorAction SilentlyContinue){ Stop-Service UALSVC -Force } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "MMS" -ErrorAction SilentlyContinue){ Stop-Service MMS -Force } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "iphlpsvc" -ErrorAction SilentlyContinue){ Stop-Service iphlpsvc -Force } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "hpqams" -ErrorAction SilentlyContinue){ Stop-Service hpqams -Force } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "wscsvc" -ErrorAction SilentlyContinue){ Stop-Service wscsvc -Force } }

Invoke-Command -ComputerName $Computer -ScriptBlock { Restart-Service winmgmt -Force }

Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "hpqams" -ErrorAction SilentlyContinue){ Start-Service hpqams } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "iphlpsvc" -ErrorAction SilentlyContinue){ Start-Service iphlpsvc } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "MMS" -ErrorAction SilentlyContinue){ Start-Service MMS } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "UALSVC" -ErrorAction SilentlyContinue){ Start-Service UALSVC } }
Invoke-Command -ComputerName $Computer -ScriptBlock { if (Get-Service "wscsvc" -ErrorAction SilentlyContinue){ Start-Service wscsvc } }

} Tee-Object -file c:\Scripts\WMI-Output.txt

1 个答案:

答案 0 :(得分:0)

作为PetSerAl hints at,您无法直接从foreach(){}循环管道输出。你有几个选择:

包裹子表达式:

$(foreach($i in 1..10){
  $i * $i
}) | Tee-Object -File C:\Scripts\Squares.txt

包装一个scriptblock:

&{
  foreach($i in 1..10){
    $i * $i
  }
} | Tee-Object -File C:\Scripts\Squares.txt

使用ForEach-Object代替foreach(){}

1..10 | ForEach-Object {
  $i * $i
} | Tee-Object -File C:\Scripts\Squares.txt

您的脚本也可以大大简化:

Get-Content C:\Scripts\Computers.txt |ForEach-Object {
    Invoke-Command -ComputerName $_ -ScriptBlock { 
        # Enable winmgmt standalone mode
        winmgmt -standalonehost 

        # Stop services
        Get-Service UALSVC,MMS,iphlpsvc,hpqams,wscsvc -ErrorAction SilentlyContinue |Stop-Service -Force

        # Restart winmgmt 
        Restart-Service winmgmt -Force 

        # Start services
        Get-Service hpqams,iphlpsvc,MMS,UALSVC,wscsvc -ErrorAction SilentlyContinue |Start-Service -Force
    }
} | Tee-Object -FilePath c:\Scripts\WMI-Output.txt