用户被注销时从任务计划程序运行Powershell脚本

时间:2017-02-17 19:06:08

标签: excel powershell task scheduler access

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

  1. 将Excel文件从映射驱动器复制到远程服务器
  2. 打开Excel文件并运行
  3. 宏复制远程服务器上的Access表并将其粘贴到Excel文件中,然后对数据进行一些操作
  4. 保存Excel文件,关闭它,然后将其复制回映射的驱动器
  5. 现在,我正在我的本地计算机上测试它,因此它将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 $_ }
    

    我需要让脚本每天在半夜运行一次,所以我一直在努力使它成为预定的任务。我首先使用以下信息设置'Action':

    编程/脚本: C:\ WINDOWS \ SYSTEM32 \ WindowsPowerShell \ V1.0 \ powershell.exe 添加参数(可选): -NoProfile -ExecutionPolicy Bypass -file“C:\ Users \ nelsonth \ emsUpdateDesktop.ps1”

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

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

    我需要这个才能工作,所以任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

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

尝试在脚本顶部添加以下内容,检查驱动器号,然后在未找到时映射:

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