2016-04-08 101 views
1

我想安排一個Powershell腳本,其參數與schtasks.exe中有一個空間。 (Powershell版本2,Windows 7)。銘記我在這個論壇上,我想出了這個表達式讀過到PowerShell的命令行中輸入:schtasks與Powershell和腳本與參數中的空間

schtasks.exe /create /f /tn "Mytaskname" /tr "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -command \`"& \`'D:\myscript.ps1\`' \`'D:\Filename with Space.xml\`'" /SD 08/04/2016 /ST 09:00 /RU domain\username /RP /SC ONCE 

不幸的是這doesn'nt工作。如果我安排任務手動將其作品展示了我下面的條目在任務計劃器:

PROGRAMM /腳本

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe 

添加參數(可選)

-command "& 'D:\myscript.ps1' ''D:\Filename with Space.xml '" 

有人能幫忙嗎? 在此先感謝

回答

0

閱讀有關轉義規則:

  • command line&在雙引號字符串已經轉義符號字符)在powershell
  • (逃避""嵌入式雙引號)
  • 中的schtasks .exe(轉義\"嵌入雙引號:通過示例學習this description

在以下批處理腳本中進行測試。請注意0​​中的-command參數允許觀察powershell腳本的結果以進行調試;輔助ST*變量僅用於更好的可讀性(STn =名稱,STe =可執行文件,STc =命令,STp =參數):

@ECHO ON 
@SETLOCAL EnableExtensions 
set "STn=MyTaskName" 
set "STe=%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" 
set "STc=D:\PShell\SO\36493932 with spaces.ps1" 
set "STp=D:\bat\a b\testfile.txt" 
schtasks.exe /create /f /tn "%STn%" /tr "%STe% -command & \"\"\"%STc%\"\"\" \"\"\"%STp%\"\"\";pause" /SC ONCE /SD 10/04/2016 /ST 11:00 
@rem /RU %USERDOMAIN%\%username% /RP 
@timeout /T 3 >NUL 
schtasks /Run /TN "%STn%" 
@pause 
schtasks /End /TN "%STn%" 

及以下powershell腳本(雖然這並不重要):

param([string] $InObject = $MyInvocation.InvocationName) 
"{0} {1}" -f "listing:", "$InObject" 
Get-Content "$InObject" 

輸出(注意,powershell腳本輸出可見在另一個窗口):

==> D:\bat\SO\36472103.bat 

==> set "STn=MyTaskName" 

==> set "STe=C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" 

==> set "STc=D:\PShell\SO\36493932 with spaces.ps1" 

==> set "STp=D:\bat\a b\testfile.txt" 

==> schtasks.exe /create /f /tn "MyTaskName" /tr "C:\Windows\system32\WindowsPowerShell\v1. 
0\powershell.exe -command & \"\"\"D:\PShell\SO\36493932 with spaces.ps1\"\"\" \"\"\"D:\bat\ 
a b\testfile.txt\"\"\";pause" /SC ONCE /SD 10/04/2016 /ST 11:00 
SUCCESS: The scheduled task "MyTaskName" has successfully been created. 

==> schtasks /Run /TN "MyTaskName" 
SUCCESS: Attempted to run the scheduled task "MyTaskName". 
Press any key to continue . . . 

==> schtasks /End /TN "MyTaskName" 
SUCCESS: The scheduled task "MyTaskName" has been terminated successfully. 

==> 
1

我忽略了模擬「添加參數(可選)」 的字符串時,手動調度帶有空格參數的powershell scirpt時效果很好。 我將JosefZ的cmd腳本轉換爲powershell腳本。

$Taskname = "MyTaskName" 
$Powershellpath = "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" 
$Powershellscript = "D:\PShell\SO\36493932 with spaces.ps1" 
$Argument = "D:\bat\a b\testfile.txt" 
$userdomain = 「Domain」 
$username = 「User」 

schtasks.exe /create /f /tn $Taskname /tr "$Powershellpath -command & \""\""\""$Powershellscript\""\""\"" \""\""\""$Argument\""\""\""" /SC ONCE /SD 10/04/2016 /ST 11:15 /RU $userdomain\$Username /RP 

if($LASTEXITCODE -eq 0) 
{ 

    start-sleep -s 3 
    schtasks /Run /TN $Taskname 
    start-sleep -s 3 
    schtasks /End /TN $Taskname 
}