Write to file in Foreach loop

Hello,

I have an script that collects the service status for machines in a list and writes the output to a csv file:

$file= "C:\temp\wk.txt"
$cre= Get-Credential "ENTER YOUR CREDENTIAL"
Get-Content $file |
ForEach-Object {
    #ICMP test 4 packets
    If(Test-Connection -ComputerName $_ -count 1 -Quiet ){
        #Read service state
        Get-WmiObject -Class Win32_Service -Filter "name='service1' or name='service2'" -ComputerName $_ -Credential $cre -ErrorAction SilentlyContinue
    }
    #If ICMP fails
    Else{New-Object PSObject -Property @{Name="N/A";State="OFFLINE";SystemName=$_}
    } 
} | Select Name,State,SystemName | Sort SystemName,Name | Export-Csv "C:\temp\wk_service_result_new.csv" -NoTypeInformation

The problem is that the script write to the file only when it goes through all machines and the list have more than 2000 machines so it takes too long to finish and if somehow my computer crash or even the script process and end-up with no result.

Is there any method I can use to make the script the result right right after it finishes on a machine instead waiting it to finish with all of them?

Thanks in advance.

September 4th, 2015 4:21am

Turns out the problem was the Sort instruction I've placed between the Select and the Export-CSV.

I deleted that and it started working just nice.

Thanks anyway.

  • Marked as answer by H Souza 22 hours 45 minutes ago
Free Windows Admin Tool Kit Click here and download it now
September 4th, 2015 4:31am

Turns out the problem was the Sort instruction I've placed between the Select and the Export-CSV.

I deleted that and it started working just nice.

Thanks anyway.

  • Marked as answer by H Souza Friday, September 04, 2015 8:27 AM
September 4th, 2015 8:27am

Turns out the problem was the Sort instruction I've placed between the Select and the Export-CSV.

I deleted that and it started working just nice.

Thanks anyway.

  • Marked as answer by H Souza Friday, September 04, 2015 8:27 AM
Free Windows Admin Tool Kit Click here and download it now
September 4th, 2015 8:27am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics