代码之家  ›  专栏  ›  技术社区  ›  Kade Williams

如何使用PsCustomObject获取计算机名?

  •  0
  • Kade Williams  · 技术社区  · 7 年前

    我目前有一个脚本,可以ping服务器列表并检查每台服务器上运行的服务的状态。我想写日志。csv。

    我想显示哪些计算机处于脱机状态,哪些服务处于停止状态。

    如何使用PSCustumObject获取计算机或计算机名称?CSV输出只有一行文字表示离线,但前面没有列出计算机名。

    $serviceList = Get-Content C:\services.txt
    
    $results = Get-Content C:\servers.txt | ForEach-Object {
        if (Test-Connection -ComputerName $_ -BufferSize 16 -Count 1 -EA 0 -Quiet) {
            foreach ($service in $serviceList) {
                if ($s=get-service -computer $_ -name $service -ErrorAction SilentlyContinue)
                {
                    $s | select MachineName, ServiceName, Status, StartType
                } else {
                    # "$_ - Service '$service' does not exist."
                }
            }
        } else {
            $status = Write-Output "Offline"
        }
    
        [pscustomobject][ordered]@{
            Machine = $_
            Status = $status
        }
    }
    
    $results | Export-CSV C:\log.csv -notypeinformation -Append
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   henrycarteruk    7 年前

    当您从输出结果时 Get-Service 您正在选择 MachineName :

    $s | select MachineName, ServiceName, Status, StartType
    

    然后,对于脱机计算机,您正在使用 Machine :

    [pscustomobject][ordered]@{
        Machine = $_
        Status = $status
    }
    

    您需要将自定义对象更新为 机器名称 因此它与您在上面选择的属性相匹配。

    它还需要进入 else{} (更换 $status = Write-Output "Offline" )因此,它仅在计算机脱机时调用。

    然后,您将获得预期的输出:

    MachineName ServiceName    Status StartType
    ----------- -----------    ------ ---------
    localhost   spooler       Running Automatic
    localhost   DusmSvc       Running Automatic
    localhost   DeviceInstall Stopped    Manual
    noname                    Offline          
    

    更新的代码,对不存在的服务进行额外更新:

    $serviceList = Get-Content C:\services.txt
    
    $results = Get-Content C:\servers.txt| ForEach-Object {
        if (Test-Connection -ComputerName $_ -BufferSize 16 -Count 1 -EA 0 -Quiet) {
            foreach ($service in $serviceList) {
                if ($s = get-service -computer $_ -name $service -ErrorAction SilentlyContinue) {
                    $s | select MachineName, ServiceName, Status, StartType
                }
                else {
                    [pscustomobject][ordered]@{
                        MachineName = $_
                        ServiceName = $service
                        Status  = "NotFound"
                    } 
                }
            }
        }
        else {
            [pscustomobject][ordered]@{
                MachineName = $_
                Status  = "Offline"
            } 
        }
    }
    
    $results | Export-CSV C:\log.csv -notypeinformation -Append