2
votes

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
3
Is the problem that the script doesn't execute properly on the schedule, or that it doesn't behave as desired even when you run it manually? If the latter, please distill the script down to the minimum possible to demonstrate the problem. - alroc
If I run the script manually it works as intended. Its just not running on Task Scheduler, it only opens the script on Notepad every 5 minutes. - mario
OK, then showing the script here isn't contributing anything. Show how you've scheduled the script in Task Scheduler, as that is the source of your problem. - alroc
I updated the description and mentioned how I scheduled it - mario

3 Answers

9
votes

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.

1
votes

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.

0
votes

Try using this CMD wrapper file to launch from the task scheduler and then name it runYour-PS1-filename.cmd. The file will create an error log and std-out log:

@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