用PowerShell调度任务

时间:2015-03-02 12:18:14

标签: powershell scheduled-tasks powershell-v3.0 webclient-download schtasks.exe

我正在尝试在远程计算机上安排任务,我在该计算机上成功安排了远程计算机上的任务未执行。就像我想在一些触发时间下载一个文件。 在我的任务计划程序中,它显示任务已成功完成,但我没有看到任何文件已下载。

 $ComputerName = "win12"
 $cr=Get-Credential $ComputerName\administrator    
 $Session = New-PSSession -ComputerName $ComputerName -Credential $cr

 Invoke-Command -Session $Session -ScriptBlock {       
     $start = (Get-Date).AddMinutes(1).ToString("HH:mm:ss")
    [string]$Result = schtasks /create /tn "kk" /tr "powershell.exe (New-Object System.Net.WebClient).DownloadFile('http://server12/vdir/OracleXE.exe','C:\abc.exe')" /sc once /st $start /ru "administrator" /rp "passw0rd@12" 
     $Result += schtasks /run /tn "kk"

    $Result

}

即使触发了时间或者我强制任务运行,也不会下载该文件。当我单独运行命令时,它可以很好地下载文件,但不能使用任务调度程序。

2 个答案:

答案 0 :(得分:0)

您似乎遇到了kerberos doublehop委托问题。我的建议:

  1. 创建ps1文件并安排脚本文件
  2. 在Invoke-command
  3. 中设置并使用CredSSP进行验证
  4. 可能是预定的工作比预定的任务更适合这种情况。

答案 1 :(得分:0)

问题是如何在powershell和schtasks中处理引号。由于/ tr命令需要用双引号括起来,因此在命令内需要双引号的地方使用单引号。这些又转换为双引号。这与powershell.exe不兼容,因为它反过来不能解释命令中的双引号。

到目前为止,我找到的唯一解决方法是将命令转换为Base64,它保留命令的确切格式,并使用-encodedCommand参数将其传递给powershell.exe

$ComputerName = "win12"
$cr=Get-Credential $ComputerName\administrator    
$Session = New-PSSession -ComputerName $ComputerName -Credential $cr

$command = "(New-Object System.Net.WebClient).DownloadFile('http://server12/vdir/OracleXE.exe','C:\abc.exe')"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)

Invoke-Command -Session $Session -ScriptBlock {       
    $start = (Get-Date).AddMinutes(1).ToString("HH:mm:ss")
    [string]$Result = schtasks /create /tn "kk" /tr "powershell.exe -encodedCommand $encodedCommand" /sc once /st $start /ru "administrator" /rp "passw0rd@12" 
    $Result += schtasks /run /tn "kk"

    $Result
}

<强>更新
另一种可能稍微复杂但需要PowerShell 3.0的方法是使用预定作业。

$ComputerName = "win12"
$cr=Get-Credential $ComputerName\administrator    
$Session = New-PSSession -ComputerName $ComputerName -Credential $cr

$command = {(New-Object System.Net.WebClient).DownloadFile(
    'http://server12/vdir/OracleXE.exe','C:\abc.exe')}

Invoke-Command -Session $Session -ScriptBlock {
  Register-ScheduledJob -Name kk -ScriptBlock $command;
  (get-scheduledjob kk).Run() }
}
相关问题