How can I redirect PowerShell output when run from Task Scheduler?

前端 未结 9 951
我在风中等你
我在风中等你 2020-12-13 12:35

When running a simple PowerShell script from Task Scheduler, I would like to redirect the output to a file.

There is a long thread about this very topic here, yet i

相关标签:
9条回答
  • 2020-12-13 13:17

    Here is the command that worked for me. I didn't like the idea of redirecting the output in the script, since it would make it difficult to run manually.

    powershell -windowstyle minimized -c "powershell -c .\myscript.ps1 -verbose >> \\server\myscript.log 2>&1"
    
    0 讨论(0)
  • 2020-12-13 13:19

    I use the transcript feature to help with this. Just include it in your code and it outputs all (would be) screen content to a log file.

        Start-Transcript -path $LogFile -append
    
        <Body of the script>
    
        Stop-Transcript
    
    0 讨论(0)
  • 2020-12-13 13:25

    I would do:
    Create a function to call your script and redirect the output of this function like this:

    .ps1:

    function test{
        # Your simple script commands
        ls c:\temp -Filter *.JPG
        ls z:\ # Non-existent directory
    }
    
    test *> c:\temp\log.txt
    

    Here is the log file:

        Répertoire : C:\temp
    
    
    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    -a---        07/06/2008     11:06     176275 HPIM1427.JPG
    -a---        07/06/2008     11:06      69091 HPIM1428.JPG
    -a---        07/06/2008     11:06     174661 HPIM1429.JPG
    
    
    ls : Lecteur introuvable. Il n'existe aucun lecteur nommé « z ».
    Au caractère C:\temp\test.ps1:14 : 1
    + ls z:\ #non existent dir
    + ~~~~~~
        + CategoryInfo          : ObjectNotFound: (z:String) [Get-ChildItem], Driv
       eNotFoundException
        + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetC
       hildItemCommand
    

    You can control what do you want to output with the new V3 redirection operators:

    Do-Something 3> warning.txt  # Writes warning output to warning.txt
    Do-Something 4>> verbose.txt # Appends verbose.txt with the verbose output
    Do-Something 5>&1            # Writes debug output to the output stream
    Do-Something *> out.txt      # Redirects all streams (output, error, warning, verbose, and debug) to out.txt
    
    0 讨论(0)
提交回复
热议问题