在任务计划程序中传递 Powershell 参数

Myr*_*ers 10 powershell scheduled-tasks

function ServiceRestart
{
    Param
    (
        $ErrorLog,
        $Services,
        $MaxSize    
    )

    $Time = Get-Date -Format 'yyyy:MM:dd HH:mm:ss'
    $Result = (Get-Item $ErrorLog).length 


    if($Result -gt $MaxSize)
    {
        Clear-Content $ErrorLog
    }

    Try 
    {
        Foreach($Service in $Services)
        {
            Restart-Service -DisplayName $Service -ErrorAction Stop
        }
    } Catch 
      {
        "ERROR: $Service could not be restarted $Time" | Add-Content $ErrorLog 
      }
}

ServiceRestart -ErrorLog -Services -MaxSize
Run Code Online (Sandbox Code Playgroud)

我需要从 Task Scheduler
- Errorlog
- Services
- MaxSize 传入以下参数

我目前的任务计划程序设置如下
程序/脚本:C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

添加参数(可选):-
Command "& \ServerName\C$\Users*****\Documents\Scripts\Scheduled-ServiceRestart.ps1
-ErrorLog 'ServerName\C$\Users*****\Documents\log \ScriptErrors.txt'
-Services 'foo1', 'foo2'
-MaxSize '5MB'"

当我运行计划任务时,什么也没有发生,可能是哪里出了问题。

Bil*_*art 12

我建议安排任务使用-File参数而不是-Command. 例子:

程序/脚本: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

添加参数(可选): -NoProfile -ExecutionPolicy Bypass -File "Scheduled-ServiceRestart.ps1" -ErrorLog "ScriptErrors.txt" -Services "foo1","foo2" -MaxSize 5MB

开始(可选): C:\Users\<username>\Documents\Scripts

您可以在任务的“开始于”属性中指定脚本的起始目录,并避免脚本和日志文件的冗长路径名。(请注意,我假设您正在本地计算机上运行脚本的副本,而不是通过网络,这会增加潜在的复杂性和失败的可能性。)

  • 由于诸如“Scheduled-ServiceRestart.ps1”之类的参数值周围有单引号,我无法使用此处显示的示例。相反,我用双引号替换了所有单引号,这解决了我的所有问题。如果在处理 Windows 命令行时发现,您应该使用双引号,因为单引号仅在极少数情况下使用。 (2认同)