我的 txt 文件中有 140 个服务器的列表,需要检查每个服务器上的 Crowdstrike 状态,然后导出到 CSV。下面的说法正确吗?
$Computers = Get-Content -Path C:\temp\servers.txt
ForEach($Computer in $Computers){
Get-Service -Displayname "Crowdstrike Falcon Sensor Service"| select Status | export-csv c:\temp\results.csv -NoTypeInformation -Append
}
我已经尝试了上述方法,结果出现错误。
正如 Santiago 所指出的,您没有在循环体中使用
$Computer
循环变量,因此所有 Get-Service
调用都是在 本地进行的。
在 Windows PowerShell 中,选择特定用途的 cmdlet,例如
Get-Service
它们自己 具有 -ComputerName
参数,因此以下可能适合您:
# Windows PowerShell only.
# If this doesn't work, see the Invoke-Command solution below.
$Computers |
ForEach-Object {
$computer = $_
Get-Service -ComputerName $computer -Displayname 'Crowdstrike Falcon Sensor Service' |
Select-Object @{ n='Computer'; e={ $computer } }, Status
} |
Export-csv c:\temp\results.csv -NoTypeInformation
在 PowerShell (Core) 7+ 中,不再支持这些
-ComputerName
参数,因为它们依赖于已从现代跨平台 .NET (Core) 框架中删除的过时的 .NET Remoting API它是 PowerShell(核心)的基础。
Invoke-Command
、Enter-PSSession
)和 CIM cmdlet(例如 Get-CimInstance
)具有 -ComputerName
参数并使用 PowerShell 的基于 WinRM 的 remoting,这是防火墙友好的。
因此 - 假设目标服务器设置为 PowerShell 远程处理 - 使用以下命令(也适用于 Windows PowerShell):
Invoke-Command -ComputerName $Computers {
Get-Service -Displayname 'Crowdstrike Falcon Sensor Service'
} |
Select-Object PSComputerName, Status |
Export-csv c:\temp\results.csv -NoTypeInformation
-ComputerName
接受计算机名称的数组,这不仅缩短了代码,还允许计算机并行成为目标。