Search code examples
powershellexport-to-csvjobs

Start-Job output in CSV format


How to get the jobs output in an CSV format. When I execute the command below, I get the output on the screen, but when I export it to CSV it does not have the same format.

$wmidiskblock = {
    Get-WmiObject -ComputerName $args[0] -Class Win32_LogicalDisk -Filter "DeviceID='C:'" |
        Select-Object Size, Freespace
    (Test-Connection -ComputerName $args[0] | Select-Object -ExpandProperty IPV4Address) |
        Select-Object IPAddressToString -Unique
    Get-Service -ComputerName $args[0] | ? {
        ($_.DisplayName -match "VMWARE") -and
        ($_.Name -notmatch "mbcs") -and
        ($_.Name -notmatch "vmvss") -and
        ($_.Name -notmatch "vmware-autodeploy-waiter") -and
        ($_.Name -notmatch "vmware-network-coredump") -and
        ($_.Name -notmatch "VMWareNetworkCoredumpWebserve") -and
        ($_.Name -notmatch "vsan-health")
    } -ErrorAction Stop
}

$com = @()
$com = "Server-x" , "Server-y"
$pop = @() 

foreach ($ser in $com) {
    [array]$pop += Start-Job -ArgumentList $ser -ScriptBlock $wmidiskblock -Name top1
}

Get-Job -Name top1 | Receive-Job -Keep

Actual output:

Size       : 64422408192
Freespace  : 4908081152
RunspaceId : cdb3xxxxx-xxxx-xxxx-xxxx-xxxxxxxxx

IPAddressToString : x.x.x.x
RunspaceId        : cdb3xxxxx-xxxx-xxxx-xxxx-xxxxxxxxx

Status      : Running
Name        : client_service
DisplayName : VMware Horizon Client

Status      : Running
Name        : ftnlsv3hv
DisplayName : VMware Netlink Supervisor Service

Status      : Running
Name        : ftscanmgrhv
DisplayName : VMware Scanner Redirection Client

Server-x

Desired output (as a CSV file):

Server Totalspace in GB    Freespace in GB IP  VMware ESX Agent Manager    VMware Inventory Service
Server-x    100 36  144.215.150.67  Running Running

Solution

  • You need to transform your data to something that's actually exportable to CSV. Basically that means you need to take the bits of information you extract from the servers and put it into one object for each server:

    $wmidiskblock = {
        $disk = Get-WmiObject ...
        $addr = (Test-Connection ...
        $svc  = Get-Service ...
    
        $prop = [ordered]@{
            Server = $args[0]
            Totalspace = $disk.Size
            Freespace  = $disk.Freespace
            IP         = $addr
        }
        $svc | ForEach-Object { $prop[$_.Name] = $_.Status }
    
        New-Object -Type PSObject -Property $prop
    }
    

    Then you can export the data received from the jobs like this:

    ... | Receive-Job | Export-Csv 'C:\path\to\output.csv' -NoType -Append