Skip to main content
 首页 » 编程设计

PowerShell 添加任务以运行带参数的 PowerShell 脚本

2025年12月25日42exmyth

我正在尝试从 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 脚本中将 ' 与\\\`"交换

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

所以任务计划程序显示
PowerShell "& \"C:\Program Files (x86)\MyDir\MyScript.ps1\" Cat 0"