Only shows one computer name instead of many systems in servers.txt

时间:2015-09-01 22:54:51

标签: powershell

I am trying to run this simple script to get the services and the accounts that are running them. My problem is that the data looks correct in the report but the server name does not change in the report. Here is the code.

$servers = get-content C:\temp\servers.txt
foreach ($server in $servers)
{
    Get-WmiObject win32_service | Select-Object -Property SystemName, DisplayName, startname | format-list -GroupBy startname | Out-File c:\temp\results.txt
}

1 个答案:

答案 0 :(得分:2)

这样可行。

$servers = get-content C:\temp\servers.txt
    foreach ($server in $servers)
    {
     Get-WmiObject win32_service -Computername $server | Select-Object -Property SystemName, DisplayName, startname | format-list -GroupBy startname | Out-File -append c:\temp\results.txt
    }

您也可以使用以下内容,但注意SystemName不是Win32_Service的属性。要解决此问题,尝试使用Get-Service | Select -first 1 | Get-Member将显示可用属性(对不起,如果这是错误的术语),重要的是MachineName,因此替换MachineName的SystemName,您将获得所需的结果。查看Hey Scripting Guy文章以获取更多信息。例如,this page

gc .\Servers.txt | foreach {get-service -ComputerName $_ | `
Select-Object -Property MachineName, DisplayName, startname | `
format-list -GroupBy startname | Out-File -append c:\temp\results.txt}

注意,我使用反引号`来使命令可读,粘贴到Powershell ISE中以保存/运行脚本或只是将行粘贴到控制台并按两次输入以运行多行脚本