We help IT Professionals succeed at work.

CANNOT Get PShell Working On Windows 2012 R2 Via Task Scheduler

Michael O'Hara
on
82 Views
Last Modified: 2017-03-09
Am trying to run script to archive files - the job runs perfectly running manually & through command prompt, but will not complete when run via Task Scheduler (even though it says the job ran).

I have seen (many) articles with switches and different ways to get around this but no luck.   Have confirmed account has "log on as batch" rights and also a local admin.   Also has rights to the network folder.

function doTheSort([string]$SourceDir, [string]$DestinationDir) 
{$files = get-childitem $SourceDir -Include @("*.txt","*.log", "*.gtm", "*.x340", "p*") 
 #$files = get-childitem $SourceDir -Exclude @("Archive","BAI Files","ICMS Output","restore","TEST-ARCH")
    
    foreach ($file in $files)
    {
        $Directory = $DestinationDir + "" + $file.lastwritetime.Date.ToString('yyyy') + "\" + $file.lastwritetime.Date.ToString('MMM') + "\" + $file.lastwritetime.Date.ToString('dd')

        if (!(Test-Path $Directory))
        {
            New-Item $directory -type directory
        }
        Copy-Item $file.fullname $Directory 
    }
}

doTheSort "I:\Prior Day files for Upload" "C:\DIR-TEST\"

Open in new window


Any suggestions?
Comment
Watch Question

Qlemo"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
Top Expert 2015

Commented:
Have you tried to run it "only when logged in", and assigning the same account which you use to log in, and then trigger the task manually with -NoExit?

The task status (sadly) only tells you that the PowerShell command itself has been issued correctly, nothing about the script status ...

Author

Commented:
Qlmeo - that run successfully.   Problem is I cannot stay logged in.    Does this result point you to something else in Task Sched?
Qlemo"Batchelor", Developer and EE Topic Advisor
CERTIFIED EXPERT
Top Expert 2015

Commented:
So doing exactly the same (stay logged in, but set the task to "whether logged in or not") does stop the script from working?
Most important advice if you need to debug for yourself: Only change one option, switch etc. at one time, and start with something working.

Sadly we see a lot of issues with Task Scheduler, PowerShell and logged-out sessions, and often are not able to locate the culprit, because it depends on the environment. This case here should allow Experts to try to perform some tests themselves. But no promise :p.
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

Commented:
oBda - you are on your game.   Worked like a charm... thanks.