Powershell 脚本从 .txt 文件中提取服务器/计算机列表,然后显示状态,然后导出到 CSV?

问题描述 投票:0回答:1

我的 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 
}

我已经尝试了上述方法,结果出现错误。

powershell server agent
1个回答
0
投票

正如 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(核心)的基础。

    • 现在,只有专用远程 cmdlet(

      Invoke-Command
      Enter-PSSession
      )和 CIM cmdlet(例如
      Get-CimInstance
      )具有
      -ComputerName
      参数并使用 PowerShell 的基于 WinRM 的 remoting,这是防火墙友好的。

      • 从 Windows Server 2012 开始的服务器版本中默认设置 PowerShell 远程处理。
    • 因此 - 假设目标服务器设置为 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
        接受计算机名称的数组,这不仅缩短了代码,还允许计算机并行成为目标。
      • 但是,请注意,输出对象的顺序通常不会反映计算机名称的输入顺序。
© www.soinside.com 2019 - 2024. All rights reserved.