【问题标题】:PowerShell add Task to run PowerShell script with parametersPowerShell 添加任务以使用参数运行 PowerShell 脚本
【发布时间】:2013-05-19 09:41:42
【问题描述】:

我正在尝试从 PowerShell 脚本将任务添加到任务计划程序,该脚本将运行带有参数的 PowerShell 脚本。

文件路径中的空格与整个命令周围的必要引号冲突,SCHTASKS 将 ' 转换为 ",因此我无法正确封装。

$command = "PowerShell \`"& 'C:\ProgramFiles (x86)\MyDir\MyScript.ps1' $myStringParam $myBooleanParam\'"" 
Write-Host $command # This outputs: PowerShell \"& 'C:\Program Files (x86)\MyDir\MyScript.ps1' Cat 0\"  
SCHTASKS /Create /TN "MyTask" /TR "$command" /SC DAILY /ST 01:30:00 /RL Highest /EC ScriptEvents /RU SYSTEM

但任务计划程序将操作显示为:

PowerShell "& "C:\Program Files (x86)\MyDir\MyScript.ps1" Cat 0"

" 和 " 相互抵消,因为这里 ' 总是切换到 ",因此任务失败。

【问题讨论】:

    标签: powershell windows-task-scheduler


    【解决方案1】:

    通过使用 \" 作为内引号来解决它。必须在 PowerShell 脚本中将 ' 与 \\\`" 交换

    $command = "PowerShell \`"& \\\`"C:\ProgramFiles (x86)\MyDir\MyScript.ps1\\\`" $myStringParam $myBooleanParam\'"" 
    

    所以任务计划程序显示

    PowerShell "& \"C:\Program Files (x86)\MyDir\MyScript.ps1\" Cat 0"
    

    【讨论】:

      【解决方案2】:

      尝试使用powershell.exe的-File参数指定要运行的脚本,在最后加上脚本的参数

      powershell.exe -File "C:\Program Files (x86)\MyDir\MyScript.ps1" Cat 0
      

      更新

      布尔和开关参数似乎是problemwith-File。这将起作用:

      powershell.exe "C:\Program Files (x86)\MyDir\MyScript.ps1" Cat 0
      

      【讨论】:

      • 尝试了很多次,都不起作用,因为 PowerShell 无法将字符串中的 0(或 $false)转换为布尔值。
      • @Brent:似乎是一个已知问题。用修复更新了我的答案
      【解决方案3】:

      对powershell使用-command参数:

      在没有任务 sceulder 的情况下你会在你的 powershell 中执行什么:

      C:\Scripts\mypsscript.ps1 -parameter 'nice value'
      

      你给任务调度器的是什么:

      要运行的程序: 电源外壳

      参数:

      -Command "& C:\Scripts\mypsscript.ps1 -parameter 'nice value'"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 2016-06-19
        相关资源
        最近更新 更多