Write-Host result to a text file

I have a code which basically checks for a service status & display the the result in console.
I am now, trying to write the console output to a text file.

Ex: If the service is not running, it has to record as service not running.
But the script is giving me wrong result. Service is running, even though, it is recording as “NOT running” to text file.
Below is the script:

$servers = Get-Content -Path C:\test\Servers.txt
ForEach ($server in $servers) {Get-service -ComputerName $server -Name ccmsetup }
if ($check -eq $null) {
Write-Output "Process is not running on $server" >> C:\test\result.txt

Can some guide me, where is the issue is?


You do not assign something to your variable $check. At least not in the code you show. Get-Service already gives you the output to the console. So you do not need to use Write-Output and you just have to export this to your results file. You could do it like this:

$servers = Get-Content -Path C:\test\Servers.txt
ForEach ($server in $servers) {
Get-service -ComputerName $server -Name ccmsetup -OutVariable Result
If($Result.Status -eq ‘Stopped’){
$Result | Out-File -FilePath C:\test\result.txt

Can you please guide me in getting the server name in the output?


$Server | Out-File -FilePath C:\test\result.txt

He probably wants to append it in the loop:

"the server is $Server, the result is $result" | Out-File -FilePath C:\test\result.txt -append