Write-Host result to a text file

Welcome Forums General PowerShell Q&A Write-Host result to a text file

This topic contains 4 replies, has 3 voices, and was last updated by

js
 
Participant
3 months, 2 weeks ago.

  • Author
    Posts
  • #103945

    Participant
    Points: 0
    Rank: Member

    Hi,
    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?

    Thanks,
    Kalyan

  • #103949

    Participant
    Points: 9
    Rank: Member

    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
        }
    }
  • #103961

    Participant
    Points: 0
    Rank: Member

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

    -Kalyan

    • #103967

      Participant
      Points: 9
      Rank: Member
      $Server | Out-File -FilePath C:\test\result.txt
    • #103985
      js

      Participant
      Points: 8
      Rank: Member

      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

The topic ‘Write-Host result to a text file’ is closed to new replies.