Powershell Write-Host append to text file - computer name and time stamp

后端 未结 3 1498
执念已碎
执念已碎 2020-12-18 22:26

I am a Powershell noobie and I am currently writing my second script so bear with me. I am trying to do a write-host and output my write-host message along with

相关标签:
3条回答
  • 2020-12-18 22:49

    Write-Host is only for sending data to the console and nowhere else. If you are looking to send data elsewhere ie. to file you will need to send it to the output stream

    write-output "folders created successfully $($env:computername)" >> c:\scripts\testlog.txt
    

    or

    "folders created successfully $($env:computername)" >> c:\scripts\testlog.txt
    

    Notice the sub expression around $env. We need to be sure that the variable is expanded in the double quotes properly.

    Look at Bacons answer for how to do this with native PowerShell cmdlets

    0 讨论(0)
  • 2020-12-18 22:52

    Use the Start-Transcript cmdlet - it can capture Write-Host output as follows:

    Start-Transcript -Path .\testlog.txt
    Write-Host "Hello World"
    Stop-Transcript
    
    0 讨论(0)
  • 2020-12-18 22:55

    Write-Host does not use standard out. It always outputs to the console directly, skipping anything else. Write-Output does output to standard out.

    To do answer your specific question -- how to append the output of a command to a text file -- you could use:

    Write-Output "folders created successfully $env:computername" >> C:\scripts\testlog.txt
    

    However, you could also use Add-Content:

    Add-Content -Path C:\scripts\testlog.txt -Value "folders created successfully $env:computername"
    

    Or you can pipe to Out-File -Append:

    "folders created successfully $env:computername" | Out-File -FilePath C:\scripts\testlog.txt -Append
    

    Why would you use different methods? They have a few differences which you won't run into very often. The redirection operators don't give you as much control over what happens (encoding, etc.).

    0 讨论(0)
提交回复
热议问题