Share via

Need help for eporting the report csv

jay k 21 Reputation points
2021-11-17T06:49:05.787+00:00

could you pls help to get, out put from the below script.

cls
$collection = import-csv "C:\test\Servercoll.txt"

foreach ($item in $collection)
{
Try
{
get-service -computername $item.Servername | where-object {$_.StartType -like "Automatic"} | ft Status,DisplayName,StartType,MAchinename
}
catch
{
Write-Output "Unable to connect to the Computer" $item.Servername
}

}

Windows for business | Windows Server | User experience | PowerShell

2 answers

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2021-11-17T15:33:40.323+00:00

    You can use the pipeline for this. Instead of intermixing a string into the "Success" data stream, which would make getting all of the results into a usable CSV, try something like this:

    Import-Csv "C:\test\Servercoll.txt" |
        ForEach-Object {
            $sname = $_.Servername  # preserve name for any errors
            Try{
                Get-Service -computername $_.Servername -ErrorAction STOP | 
                    Where-Object {$_.StartType -like "Automatic"} | 
                        Select-Object Status,DisplayName,StartType,Machinename
            }
            Catch{
                [PSCustomObject]@{
                    Status = "Unable to connect to the Computer"    # maybe use "$_.Exception" instead of a fixed text
                    DisplayName = ""
                    StartType = ""
                    Machinename = $sname
                }
            }
        } | Export-Csv -Path "C:\test\Services.csv" -NoTypeInformation
    

    Was this answer helpful?

    0 comments No comments

  2. Clément BETACORNE 2,501 Reputation points
    2021-11-17T14:35:10.46+00:00

    Hello,

    Maybe this can help :

    cls
    $collection = import-csv "C:\test\Servercoll.txt"
    $colObjServices = @()
    foreach ($item in $collection)
    {
    Try
    {
    $objServices = get-service -computername $item.Servername | where-object {$_.StartType -like "Automatic"} | Select-Object Status,DisplayName,StartType,MAchinename
    $colObjServices = $colObjServices + $objServices
    }
    catch
    {
    Write-Output "Unable to connect to the Computer" $item.Servername
    }
    
    }
    
    $colObjServices | Export-Csv -Path "C:\test\Services.csv" -Delimiter ";" -NoTypeInformation
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.