在Windows 2016服务器中使用Powershell脚本从Windows任务计划程序启动应用程序的问题

时间:2020-01-06 14:02:35

标签: powershell

我必须使用其他服务帐户用户凭据启动应用程序,并且此工作是通过Windows任务计划程序上创建的作业完成的,该任务调用powershell脚本以服务帐户用户身份打开应用程序。问题是当从任务计划程序执行此脚本时,应用程序将永远无法启动。当我分别运行该脚本时,该脚本可以完美运行。

下面的代码将任务设置到任务计划程序中。

$scriptPath = "C:\temp\SetupTask.ps1"
$action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "PowerShell.exe -executionpolicy bypass -noprofile -file $scriptPath 2>&1 > c:\\temp\\Setuptask.txt"
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:15
$settings = New-ScheduledTaskSettingsSet -MultipleInstances Queue
Register-ScheduledTask -TaskName "RunSetup" -Principal $principal -TaskPath "\test\setup" -Trigger $trigger -Action $action -Force -Settings $settings

下面是任务计划程序执行的代码-SetupTask.ps1。

$timestamp = Get-Date
Write-Host "Setup Script Start at $timestamp"
Write-Host "Running Xapp"
& "C:\temp\RunXAppbyTask.ps1"
Unregister-ScheduledTask -TaskPath "test\setup" -TaskName "RunSetup" -Confirm:$false
$timestamp = Get-Date
Write-Host "Setup Script End at $timestamp"

下面是runXAppbyTask.ps1的代码

 $username = "XXX-DDD" + "\service_account_user"
 $password = "YYYYYY"  
 $credentialsObject = New-Object System.Management.Automation.PSCredential -ArgumentList    @($username, (ConvertTo-SecureString -String $password -AsPlainText -Force))

  $XAPPExeName = "XAPP.Client.DesktopUI"  
  $XAPPPath = "C:\Program Files\XAPP\XAPPClient\" + $XAPPExeName + ".exe"

  try {
    $timestamp = Get-Date  
    Write-Host "Starting XAPP Application as $username at $timestamp"  
    Start-Process -FilePath $XAPPPath -Credential ($credentialsObject) #The aplication doesn't start up, this same script works fine when ran separately.
    Start-Sleep -s 60
    $timestamp = Get-Date
    Write-Host "Started XAPP Application as $username at $timestamp" 

    try {
      $Process = Get-Process $XAPPExeName  # Always fail to get the process since the process don't get started when called from the task scheduler
      Write-Host $Process.Id "-" $Process.Name
      if (!($Process.HasExited)) {
        Stop-Process -Name $Process.Name -Force
      }
    }
    catch {
      write-host "Error Closing the XAPP Application."
    }
    }
    catch {
    write-host "Error Starting the XAPP Application."  
  }

我确实浏览了以下链接,在我看来这似乎呼出了类似的问题,但我找不到解决该问题的方法。请注意,没有引发错误的脚本只会成功运行,但应用程序永远不会启动。在这里的任何帮助将不胜感激。预先感谢。

Thread-1

Thread-2

1 个答案:

答案 0 :(得分:0)

好像您的任务需要提升的权限才能执行它,因为我看到您正在尝试访问C:\Program Files\XAPP\XAPPClient\

您可以尝试以最高特权运行Windows任务吗?您可以通过选中安全性选项中的框来做到这一点

enter image description here