【问题标题】:Running Powershell Script from Task Scheduler when User is Logged Off [duplicate]用户注销时从任务计划程序运行 Powershell 脚本 [重复]
【发布时间】:2017-07-07 10:23:34
【问题描述】:

我有一个打算从远程服务器运行的 powershell 脚本。该脚本的目的是执行以下操作:

  1. 将 Excel 文件从映射驱动器复制到远程服务器
  2. 打开 Excel 文件并运行宏
  3. 宏复制远程服务器上的 Access 表并将其粘贴到 Excel 文件中,然后对数据进行一些操作
  4. 保存 Excel 文件,将其关闭,然后将其复制回映射的驱动器

现在,我正在本地计算机上对其进行测试,因此它将 Excel 文件从映射驱动器复制到我的 C 驱动器,然后从本地计算机上的某个位置获取 Access 表。当我从 Powershell 运行它时,它运行完美。代码如下:

# collect excel process ids before and after new excel background process is 
# started
$priorExcelProcesses = Get-Process -name "*Excel*" | % { $_.Id }
$Excel = New-Object -ComObject Excel.Application
$postExcelProcesses = Get-Process -name "*Excel*" | % { $_.Id }

#run program
$folderPath = "my folder goes here"
$filePath = "my folder gooes here\filename.xlsm"
$tempPath = "C:\Users\Public"
$tempFile = "C:\Users\Public\filename.xlsm"

#copy file from I drive to remote desktop
Copy-Item -Path $filePath -Destination $tempPath

#create Excel variables
$excel = new-object -comobject excel.application
$excel.visible = $False
$excelFiles = Get-ChildItem -Path $tempPath -Include *.xls, *xlsm -Recurse

#open excel application and run routine
Foreach($file in $excelFiles)
{
    $workbook = $excel.workbooks.open($tempFile)
    $worksheet = $workbook.worksheets.item(1)
    $excel.Run("getAccessData")
    $workbook.save()
    $workbook.close()
}

#copy file from remote desktop back onto I drive
Copy-Item -Path $tempFile -Destination $folderPath

# try to gently quit
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)

# otherwise allow stop-process to clean up
$postExcelProcesses | ? { $priorExcelProcesses -eq $null -or $priorExcelProcesses -notcontains $_ } | % { Stop-Process -Id $_ }

我需要让脚本在半夜每天运行一次,所以我一直在努力使其成为计划任务。我首先使用以下信息设置“操作”:

程序/脚本: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe 添加参数(可选): -NoProfile -ExecutionPolicy 绕过 -file "C:\Users\nelsonth\emsUpdateDesktop.ps1"

现在,如果我在安全选项设置为“仅在用户登录时运行”并选中“隐藏”复选框时运行此任务,则该任务运行完美。

因为这将在半夜从远程桌面运行,所以我需要在我注销时运行脚本。但是当我选择“无论用户是否登录都运行”和“以最高权限运行”时,脚本不再运行。

我需要它来工作,所以有人可以帮我解决这个问题吗?

【问题讨论】:

  • 我按照您对另一个问题的回答中的步骤进行操作,但它根本没有改变任何东西。
  • 我刚刚确认,按照相关问题的答案导致我在打开 Excel 时收到以下通知:“无法使用对象链接和嵌入。”然后,该应用程序无法打开我现有的任何 Excel 文件。我必须撤消建议的更改才能再次使用 Excel,所以我不会再走这条路了。

标签: excel powershell ms-access task scheduler


【解决方案1】:

当运行为“无论用户是否登录都运行”时,您的 PowerShell 脚本很可能必须手动映射驱动器或通过 UNC 路径访问文件。

尝试在脚本顶部添加如下内容,检查驱动器号,如果找不到则映射:

if (-Not (Test-Path 'X:\')) {New-PSDrive -Name "X" -PSProvider FileSystem -Root "\\MyServer\MyShare"}

【讨论】:

  • 好的,看来这已经奏效了。我必须修改 Excel VBA 代码以通过其全名而不是驱动器位置来引用映射驱动器。一旦我这样做了,无论我是否登录,它都会起作用。
猜你喜欢
  • 2020-08-07
  • 2019-10-31
  • 2019-05-08
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多