Avatar of Michael O'Hara
Michael O'Hara
 asked on

CANNOT Get PShell Working On Windows 2012 R2 Via Task Scheduler

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?
Powershell

Avatar of undefined
Last Comment
Michael O'Hara

8/22/2022 - Mon
Qlemo

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 ...
Michael O'Hara

ASKER
Qlmeo - that run successfully.   Problem is I cannot stay logged in.    Does this result point you to something else in Task Sched?
Qlemo

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.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
oBdA

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Michael O'Hara

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