Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute PowerShell script on Task Scheduler?

I am trying to execute my Powershell script to run every 5 minutes. I tried using Windows 7's Task Scheduler to run it but instead it opens my script on Notepad and doesn't INSERT anything in my database

Below is my Powershell V-2.0 script. I am not sure if I have something wrong in my code (which I doubt) or is there a way that I can include it in my script to run every 5 minutes lets say from 9am to 9pm.

Here is how I scheduled it:

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

Thanks in advance!

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
like image 748
mario Avatar asked Mar 28 '26 21:03

mario


2 Answers

The Action for your scheduled task must call powershell.exe with the script file passed as an argument. See 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

The user under which the script executes needs to have the permissions required to perform all of the actions in the script.

like image 60
alroc Avatar answered Mar 31 '26 11:03

alroc


Without the task description, it's all guessing. Anyway, it sounds like you have only specified the script to be run, not the execution engine. That is, Task Scheduler will be able to run .cmd and .bat scripts without any extra configuration. Not so with Powershell. You got to specify the task to run powershell.exe and pass path to the script file as a parameter. A trivial example is in Technet.

As why Powershell's .ps1 is different than batch, the reason is security. Instead of making Powershell scripts easy to run, a speed dump makse Powershell scripts less attractive an attack vector.

like image 37
vonPryz Avatar answered Mar 31 '26 09:03

vonPryz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!