为什么PS没有在这些txt文件中保存信息?

时间:2017-12-07 22:09:40

标签: powershell

我没有得到任何错误,而且PowerShell制作了这些文件,但它们都是空的。我错了什么?

$Services = Get-Service
Foreach ($Proces in $Services) {
If($Proces.status -eq "running") { Out-File $Proces >> "C:\proces.txt"} 
If($Proces.status -eq "stopped") { Out-File $Proces >> "C:\proces2.txt"} 
}

1 个答案:

答案 0 :(得分:1)

>> is the append redirect operator,与Out-File -Append基本相同。所以这就像两次调用Out-File一样。

使用命令Out-File $Proces >> "C:\proces.txt",您不会将输入对象传递给Out-File。所以你写一个空白文件到$Proces。然后获取该命令的输出(无)并将其写入C:\proces.txt,这将创建第二个空白文件。

因此,您需要决定使用Out-File -Append还是>>

以下是仅使用Out-File的代码:

$Services = Get-Service
Foreach ($Service in $Services) {
    If ($Service.Status -eq "Running") { Out-File -InputObject $Service -Path "C:\proces.txt" -Append} 
    If ($Service.Status -eq "Stopped") { Out-File -InputObject $Service -Path "C:\proces2.txt" -Append } 
}

以下是仅使用>>的代码:

$Services = Get-Service
Foreach ($Service in $Services) {
    If ($Service.Status -eq "Running") { $Service >> "C:\proces.txt" } 
    If ($Service.Status -eq "Stopped") { $Service >> "C:\proces2.txt" } 
}

还有很多其他方法可以做你正在尝试的事情

这是使用Where-Object cmdlet而不是循环/条件

的方法
$Services = Get-Service 
$Services | Where-Object {$_.Status -eq "Running"} | Out-File "C:\proces.txt" -Append
$Services | Where-Object {$_.Status -eq "Stopped"} | Out-File "C:\proces2.txt" -Append

以下是使用split

.where()方法的一种方法
$Running,$Stopped = (Get-Service).Where({$_.Status -eq 'Running'},'Split')
$Running | Out-File "C:\proces.txt" -Append
$Stopped | Out-File "C:\proces2.txt" -Append