PowerShell 添加任务以运行带参数的 PowerShell 脚本 [英] PowerShell add Task to run PowerShell script with parameters

查看:129
本文介绍了PowerShell 添加任务以运行带参数的 PowerShell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying add a Task to the Task Scheduler from a PowerShell script that will run a PowerShell script with parameters.

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

The spaces in the file path are conflicting with the necessary quotes surrounding the whole command, and SCHTASKS converts ' to " so I can't encapsulate properly.

$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

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

but Task Scheduler shows Actions as:

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

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

The " and " cancel each other out because ' is always switched to " here, thus task fails.

推荐答案

通过使用 \" 作为内引号解决.不得不在 PowerShell 脚本中将 ' 与 \\\`" 交换

Solved it by using \" as the inner quotes. Had to swap ' with \\\`" in PowerShell script

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

所以任务计划程序显示

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

这篇关于PowerShell 添加任务以运行带参数的 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆