How to output something in PowerShell

前端 未结 7 974
北恋
北恋 2020-12-04 07:43

I am running a PowerShell script from within a batch file. The script fetches a web page and checks whether the page\'s content is the string \"OK\".

The PowerShell

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 08:27

    I think in this case you will need Write-Output.

    If you have a script like

    Write-Output "test1";
    Write-Host "test2";
    "test3";
    

    then, if you call the script with redirected output, something like yourscript.ps1 > out.txt, you will get test2 on the screen test1\ntest3\n in the "out.txt".

    Note that "test3" and the Write-Output line will always append a new line to your text and there is no way in PowerShell to stop this (that is, echo -n is impossible in PowerShell with the native commands). If you want (the somewhat basic and easy in Bash) functionality of echo -n then see samthebest's answer.

    If a batch file runs a PowerShell command, it will most likely capture the Write-Output command. I have had "long discussions" with system administrators about what should be written to the console and what should not. We have now agreed that the only information if the script executed successfully or died has to be Write-Host'ed, and everything that is the script's author might need to know about the execution (what items were updated, what fields were set, et cetera) goes to Write-Output. This way, when you submit a script to the system administrator, he can easily runthescript.ps1 >someredirectedoutput.txt and see on the screen, if everything is OK. Then send the "someredirectedoutput.txt" back to the developers.

提交回复
热议问题