【问题标题】:Windows schedules task creation issue with powershellWindows 使用 powershell 安排任务创建问题
【发布时间】:2011-06-17 11:35:39
【问题描述】:

我正在尝试使用 powershell 编写 windows 计划任务创建脚本,其中计划任务调用包含空格的目录中的 powershell 脚本。所以我需要使用 /tr 参数创建,例如 powershell.exe -noninteractive -command "& 'c:\temp\program files\a.ps1'"

这是我尝试过的示例

# Create the script file the schedule task will call, note path contains a space
'set-content c:\temp\program files\a.log "Just done @ $(get-date)"' > 'c:\temp\program files\a.ps1'

$scriptFilePath = 'c:\temp\program files\a.ps1';
$userName = read-host 'user name'; # will need log on as batch rights 
$userPassword = read-host 'user password';

# The following looks good but schtasks args gets messed up so no creation
$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -command `"& '$scriptFilePath'`"";  
$taskToRun
schtasks /create /tn 'ATest' /ru $userName /rp $userPassword /sc MINUTE /mo 1 /st '00:00' /f /tr $taskToRun;

# Gets imported but mangles the tr so instead of 
$taskToRun = 'c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -command \"& ''' + $scriptFilePath + '''\"';
$taskToRun
schtasks /create /tn 'ATest' /ru $userName /rp $userPassword /sc MINUTE /mo 1 /st '00:00' /f /tr $taskToRun;

如果有人知道如何正确逃脱,我将不胜感激

提前致谢

拍拍

【问题讨论】:

  • Powershell 不需要分号行终止符。仅当您希望一行中有多个语句时才使用;
  • 我知道它们不是必需的,只是一种习惯
  • 有完整源代码的最终解决方案吗?

标签: powershell escaping scheduled-tasks


【解决方案1】:

我会将 -command 选项换成 -file:

$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -file ""$scriptFilePath""" 

此外,PowershellPack 有一个 TaskScheduler 模块,它使任务调度变得更加容易:

http://archive.msdn.microsoft.com/PowerShellPack

[更新]谢谢

完美,只需要用单引号而不是双引号转义

$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -file '$scriptFilePath'";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2011-01-19
    • 2011-12-31
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多