Scheduled Task for PowerShell Script with String Array Parameter

前端 未结 3 768
我在风中等你
我在风中等你 2021-01-19 02:09

I\'ve created a PowerShell script that runs perfectly from the Management Shell. I\'m trying to get it setup to work in a scheduled task in Windows Server 2008 R2 and am uns

3条回答
  •  别那么骄傲
    2021-01-19 02:49

    Another option, when the options get too complex and you're tired of fiddling with quotes, backticks, etc is to use the underused -EncodedCommand parameter on PowerShell.exe e.g.:

    C:\PS> $cmd = "c:\temp\foo.ps1 'D:\Documents\PowerShell Scripts','D:\SomeFolder'"
    C:\PS> $cmd
    c:\temp\foo.ps1 'D:\Documents\PowerShell Scripts','D:\SomeFolder'
    C:\PS> $bytes = [Text.Encoding]::Unicode.GetBytes($cmd)
    C:\PS> $encodedCmd = [Convert]::ToBase64String($bytes)
    C:\PS> $encodedCmd
    YwA6AFwAdABlAG0AcABcAGYAbwBvAC4AcABzADEAIAAnAEQAOgBcAEQAbwBjAHUAbQBlAG4AdABzAFwAUABvAHcAZQByAFMAaABlAGwAbAAgAFMAYwByAGkAcAB0AHMAJwAsACcARAA6AFwAUwBvAG0AZQBGAG8AbABkAGUAcgAnAA==
    C:\PS> powershell.exe -encodedCommand YwA6AFwAdABlAG0AcABcAGYAbwBvAC4AcABzADEAIAAnAEQAOgBcAEQAbwBjAHUAbQBlAG4AdABzAFwAUABvAHcAZQByAFMAaABlAGwAbAAgAFMAYwByAGkAcAB0AHMAJwAsACcARAA6AFwAUwBvAG0AZQBGAG8AbABkAGUAcgAnAA==
    param1[0] is D:\Documents\PowerShell Scripts
    param1[1] is D:\SomeFolder
    

    Admittedly, not something that would be exactly readable/understandable by someone else. :-) You'd have to doc the command in the description of the scheduled task.

提交回复
热议问题