首页 文章

如何在任务计划程序上执行PowerShell脚本?

提问于
浏览
1

我试图执行我的Powershell脚本每5分钟运行一次 . 我尝试使用Windows 7的任务计划程序来运行它,但它在记事本上打开我的脚本并且不会在我的数据库中插入任何内容

下面是我的Powershell V-2.0脚本 . 我不确定我的代码中是否有错误(我怀疑)或者我是否可以将其包含在我的脚本中以便每隔5分钟运行一次,从早上9点到晚上9点 .

这是我如何安排它:

General
--------
Run only when user is logged on

Triggers
--------
Trigger: at 8h56am every day- 
Details: After triggered, repeat every 5 minutes indefinitely
Status: Enabled

Actions
-------
Action: Start a program
Details: Path to the script

提前致谢!

POWERSHELL(excluding connection):

function ping_getUser{

#ping each computer if online, obtain information about the local hard drives only
TRY{
    foreach($workstation in $workstation_list){

        $command = $connection.CreateCommand();
        $command.Connection  = $connection;
        $command.CommandText = "INSERT INTO workstation_userlogged
                                (username,hostname,online)
                                VALUES (@username,@hostname,@status)";

        ### ============================================================= 
        ### values to be assigned as a parameters
        ### =============================================================           
        $hostname    = $workstation;                
        $test_ping   = Test-Connection -ComputerName $hostname -Count 1 -ErrorAction SilentlyContinue;
        $status      = [bool](Test-Connection $hostname -Quiet -Count 1 -ErrorAction SilentlyContinue);

        #if status is TRUE get username
        if($test_ping)
        {
           TRY{
                $username =( Get-WMIObject -ComputerName $hostname -Class Win32_ComputerSystem -ErrorAction Stop | Select-Object -ExpandProperty Username);
           }CATCH{
                Write-Host "Caught the exception" -ForegroundColor Red;
                Write-Host "$_" -ForegroundColor Red;
           }

          TRY{
               if( $test_ping -and $username )
               {
                    $username = $username.split("\");
                    $username = $username[1];
                    echo $username;
               }
          }CATCH{
                Write-Host "Caught the exception" -ForegroundColor Red;
                Write-Host "$_" -ForegroundColor Red;
           }

           #if ping succeeds but no user is logged
           if($test_ping -and -not $username ) # -eq "" 
           {
                $username = "No User";  
           } 
        } #end if

        #if ping DOES NOT succeed set username value to NULL and status to FALSE
        elseif(!$test_ping)
        {
                $username = [DBNull]::Value;
        }#end elseif

       ### ============================================================= 
       ### Assign parameters with appropriate values
       ### ============================================================= 
        $command.Parameters.Add("@username", $username)  | Out-Null
        $command.Parameters.Add("@hostname", $hostname)  | Out-Null
        $command.Parameters.Add("@status",   $status)    | Out-null

       ### ============================================================= 
       ### Execute command query
       ### ============================================================= 
        TRY{
            $command.ExecuteNonQuery() | out-null;
            Write-Host "Successfully inserted in Database";
        }
        CATCH{
            Write-Host "Caught the exception" -ForegroundColor Red;
            Write-Host "$_" -ForegroundColor Red;
        }

       ### ============================================================= 
       ### clear parameter values
       ### =============================================================  
        $command.Dispose()
        $hostname  = "";
        $username  = "";
        $status    = "";
        $test_ping = "";
     }#end for each loop  
}#end try
CATCH{
     Write-Host "Caught the exception" -ForegroundColor Red;
     Write-Host "$_" -ForegroundColor Red;
}#end catch
$connection.Close(); #close connection
}#end ping_test function

ping_getUser #execute function

3 回答

  • 5

    计划任务的操作必须调用 powershell.exe ,并将脚本文件作为参数传递 . 见http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx

    powershell.exe -file c:\path_to_your_script\script.ps1
    

    脚本执行的用户需要具有执行脚本中所有操作所需的权限 .

  • 1

    没有任务描述,这都是猜测 . 无论如何,听起来你只指定要运行的脚本,而不是执行引擎 . 也就是说,任务计划程序将能够运行 .cmd.bat 脚本而无需任何额外配置 . Powershell不是这样 . 您必须指定运行 powershell.exe 的任务并将路径作为参数传递给脚本文件 . trivial example在Technet中 .

    正如Powershell的 .ps1 与批次不同,原因在于安全性 . 而不是使Powershell脚本易于运行,速度转储maxtse Powershell脚本不那么有吸引力的攻击向量 .

  • 0

    尝试使用此CMD包装器文件从任务计划程序启动,然后将其命名为 runYour-PS1-filename.cmd . 该文件将创建错误日志和std-out日志:

    @echo off
    SetLocal
    REM
    REM This cmd file will launch it's corresponding PowerShell-script. 
    REM
    REM We need to change std character set to support international characters when calling 
    REM a PowerShell script. It's ohh soo 2017
    REM
    chcp 1252 > nul
    Set MyName=%~n0
    Set ErrLog="%~dp0ERR_%MyName:~3%.log"
    Set LogFile="%~dp0%MyName:~3%.log"
    
    REM This line will launch with a separate ERROR-log
    PowerShell -File "%~dp0%MyName:~3%.ps1" %* >> %LogFile% 2>&1 2>> %ErrLog%
    
    REM Remove log if empty
    findstr "^" %ErrLog% || del %ErrLog% >nul 
    
    chcp 850 > nul
    EndLocal
    

相关问题