【问题标题】:PowerShell function does not work from Windows Task SchedulerPowerShell 功能在 Windows 任务计划程序中不起作用
【发布时间】:2020-01-02 01:04:26
【问题描述】:

我正在从 PowerShell 脚本调用一个函数来更新远程服务器上的一些文件。该脚本运行良好,并在我从 ISE 运行时按预期调用该函数。但是当我使用 Windows 任务调度程序运行脚本时,该函数不会被调用。不知道在这种情况下我应该做什么。我点源函数以从脚本中调用函数。

 . “c:\temp\updatefiles.ps1” Monitoring  CUSTOMER Approved

我也试过了。

 . 'c:\temp\updatefiles.ps1' Monitoring  CUSTOMER Approved

这是函数。

Function Monitoring($NAME, $status) {

  $REMOTE_SERVER = "sasipt01"
   # change the status on the REMOTE Server - sasipt01.

   # Check if the file exists on the REMOTE Server.
    $Chk = Invoke-Command -ComputerName "$REMOTE_SERVER" -ScriptBlock {if 
      (Test-Path ' C:\Temp\filelist.csv') {'True'} else {'False'}} 

     if ($Chk = 'True') {

       # File exists on the server.

        $Input = Invoke-Command -ComputerName "$REMOTE_SERVER" -ScriptBlock 
                {Import-Csv 'C:\Temp\filelist.csv'}
        $Output = foreach ($i in $input) { 
          if ($i.Process_Instance -match "$NAME") {$i.Status = "$status"} $i } 

          $OutArray = $Output | Select-Object -Property * -ExcludeProperty 
                                    PSComputerName, RunspaceId, PSShowComputerName
          $OutArray | Invoke-Command -ComputerName "$REMOTE_SERVER" -ScriptBlock 
          {Export-Csv 'C:\Temp\filelist.csv' -NoTypeInformation}
                   }
                }

updatefiles.ps1 从主脚本 (start.ps1) 调用,该脚本从 Windows 任务调度程序执行。

我还在配置文件(AllUsersAllHosts 和 AllUsersCurrentHost)上添加了该功能,并尝试从任务调度程序运行主脚本。但是还是不行。

【问题讨论】:

  • [1] 包含函数的脚本没有调用运行任何内容。你怎么称呼它?点源仅将其加载到您的脚本中,除非有运行代码的调用,否则它不会运行它。 ///// [2] 函数是否独立运行 - 提供所需的输入?
  • [1] 删除路径 (Test-Path ' C:\Temp\filelist.csv') 中的空格。 [2] 由于脚本存储在C:\Temp 文件夹中,您的 AV 软件可能会阻止它运行,或者可能是组策略将您阻止在那里。 [3] 不要使用 $input 作为自声明变量,因为在 PowerShell 中这是一个 Automatic variable。 [4] 谁在运行计划任务?该用户是否有权这样做? (查看-ExecutionPolicy
  • 谢谢你,我按照你的建议修复了空间和变量名。由于我创建了计划任务,我假设它是以我的名义运行的。服务器上没有安装 AV 软件。还有其他运行良好的计划任务。
  • 编辑了问题并添加了我传递给函数的参数。
  • 不起作用表示您尚未进行任何故障排除。 Windows 调度程序日志和 Windows 事件日志说明了什么?

标签: powershell


【解决方案1】:

更改start.ps1 脚本以执行以下操作:

function Monitoring($Name, $Status) {
    # your code here to do things with the parameters 

    # for demo, I'll just write them out
    Write-Host $Name
    Write-Host $Status
    Read-Host
}

# call the function with the parameters supplied to the script
Monitoring $args[0] $args[1]

然后在任务计划程序中,双击任务,转到Actions 选项卡并编辑参数字段以包含以下内容:

-File "C:\Temp\start.ps1" -ArgumentList 'CUSTOMER','Approved' -ExecutionPolicy Bypass

ExecutionPolicy

General 选项卡中,您可以定义任务用户是谁以及任务是否可以在不登录的情况下运行等。

附:我建议让代码编写一个新的 csv 文件,而不是在测试期间覆盖原始文件。

希望对你有帮助

【讨论】:

  • 感谢您的帮助。我发现问题是由于本地系统帐户正在运行的任务计划程序,并且系统帐户无权访问 csv 文件所在的远程服务器。我已经更改了任务计划程序上的用户帐户并且它有效。
【解决方案2】:

我发现问题是由于本地系统帐户正在运行的任务计划程序,而系统帐户无权访问 csv 文件所在的远程服务器。我已经更改了任务计划程序上的用户帐户并且它工作了

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 2015-02-26
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 2014-12-28
    相关资源
    最近更新 更多