Schedule task running ps1 fails at some point

Hi Guys

I think I need your knowledge :slight_smile:

I made 2 scripts (merging scripts found over internet and adjusting them for by needs)

The purpose of those scritps is to check per IP range if there are Computers still turn on after 22h00 and if yes, retrieve IP,Mac, DNS name, Last Logged user and store that in a HTA file + cvs file
I dediced to run the invoke command against a server located in the scpecific Ip range to avoir any performance issue

Running those script in the ISE works perfectly. I’m able to retrieve the LastLoggedUser and even force shutdown the computers
Running in a schedule task with same credentials works but computers are not shutdown and I can’t get any name for LastLoggedUser

I tried many ways but none are working when run by a schedule task. I’m sure it is pretty simple to solve but I’m a bit lost.

Thanks for any help

One is run by a schedule task (on a W10 computer) run as “XXX\DOMAINADMIN” with this command line :
powershell.exe -ExecutionPolicy Bypass c:\temp\test.ps1

Here it is :

$pass=cat "\\COMPUTER\Temp\securecred.txt" | convertto-securestring 
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$pass

. C:\temp\PingRange.ps1
$session = New-PSSession -ComputerName SERVERX -Credential $cred
Invoke-Command -Session $session -scriptblock ${function:Get-Computer-To-Shutdown} -ArgumentList 111.111.11, 64, 70, 'ROS', $false, $cred
Remove-PSSession $session

The second one named PingRange.ps1:

Function Get-Computer-To-Shutdown {
## add to remove the synopsis as this board seems to not like it

        [Parameter(Mandatory=$true, HelpMessage="You must provide a IP addresses range to be scanned.")]
        [Parameter(Mandatory=$true, HelpMessage="You must provide the first IP address.")]
        [Parameter(Mandatory=$true, HelpMessage="You must provide the last IP address.")]
	[Parameter (HelpMessage="file prefix.")]
	[Parameter (HelpMessage="Want to shutdown ?")]
        [Parameter (HelpMessage="Credentials ?")]

    Function Get-Mac($line) {
        $macRegex=[regex] "([0-9a-fA-F]{2}-){5}([0-9a-fA-F]{2})"

    Function Get-Ping($line) {
        $pingRegex=[regex] "temps=\d+ ms"

If ($fin -lt $debut) {throw "La valeur de fin doit etre supérieure a la valeur de début"}

# Create an array with computername that shouldn't be listed/rebooted -> need to be a file in the future
$exceptions = Get-content '\\COMPUTER\Temp\Exceptions.txt'
$report="\\COMPUTER\Temp\"+$prefix+"_"+[DateTime]::Now.ToString("yyyyMMdd-HHmmss") +".hta"
$reportcsv="\\COMPUTER\Temp\"+$prefix+"_"+[DateTime]::Now.ToString("yyyyMMdd-HHmmss") +".csv"


$ScanDate=Get-Date -Format "dd/MM/yyyy HH:mm:ss"

#Write-Host "`nRunning the IP address scan for the range $`n" -ForegroundColor Yellow
$debut..$fin | ForEach {
    if ((Test-Connection -Count 1 -ComputerName "$range.$_" -Quiet)) {
        $IpAddress="$range" + "." + "$_"
        if ($computername -eq $null) {$computername = "unable to get the hostname"}
        Else {$computername = $computername -replace ".CPCORP.NET", "" }
        if (($computername -like 'DT*') -or ($computername -like 'LT*')) {
            If ($exceptions -notcontains $computername) {
				$arp=cmd /c "arp -a $IpAddress"
				$mac=Get-Mac $arp | Select-Object -ExpandProperty Value

############### Those line seems to not work when run in a schedule task
				$username =(Get-WmiObject -credential $creds Win32_ComputerSystem -ComputerName $IpAddress).Username
				If ($Shutdown) { (gwmi -credential $creds win32_operatingsystem -ComputerName $IpAddress).Win32Shutdown(12) }

                If ($Shutdown) {$status = @{'Hostname'="$computername";'MAC Address'="$mac";'IP Address'="$range.$_"; 'Status'="Shutdown Command sent";'User'="$username"} }
                Else {$status = @{'Hostname'="$computername";'MAC Address'="$mac";'IP Address'="$range.$_";'User'="$username"} }
            $obj=New-Object -TypeName PSObject -Property $status

    IP Range Scan Results 
    h1 {margin: 0; padding: 0; position: relative; background: #104E8B;color: #FFF;}
    body {font: 12px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;}
    table{border: 1px dotted #CCC; font-family: Arial, Helvetica, sans-serif; font-size: 12px; width:100%;}
    th{background-color: #104E8B; color: #FFF; font-weight: bold; text-align:left; vertical-align:top;}
    td{border: 1px dotted #CCC; text-align:left; vertical-align:top;}
    #page-wrap { width: 50%; margin: 100px auto; }
    #bottom {clear:both; text-align:right;}
     IP Range Scan Results
  • Scan Date: $ScanDate
  • IP Range scanned: $
"@ $bottom=@" © IpRangeScan.ps1 - 2012 "@ Write-Host "`nGenerating the report`n" -ForegroundColor Yellow $results| ConvertTo-Csv -NoTypeInformation -Delimiter ';' | Select -Skip 1 | Set-Content -Path $reportcsv # CSV without Header $results | ConvertTo-HTML -Head $style -Body $body -PostContent $bottom | % {$tmp = $_ -replace "";} |Out-File $report Start-Sleep 2 #Invoke-Expression $report }

This may depend on how you created the scheduled task. By default, Windows does not save the password for the account that’s running the script, and uses a special login token called S4U (Services for User). This works fine if you’re accessing local resources only, but it can’t talk to other computers over the network.

For tasks that need network access, make sure the scheduled task has the “do not save password” box unchecked (and likely the “run whether user is logged on or not” box checked.)

Hi Dave

Thx for your reply.

My bad I did not say that :
The “do not save…” is unticked
and the " run wheteruser …" is ticked.

edit : “run with High priviledge” is unticked (doesn’t work if ticked)