0

I have a simple powershell script that runs fine when I execute it from the powershell editor, but yields entirely different results when I run it from Windows Task Scheduler.

Original code is below ... simply want to copy the latest file from the m: drive.

$OriginalDir = "M:"
$BackupDir = "c:\downloads\db"
$LatestFile = Get-ChildItem -path m:  -Name -ErrorAction SilentlyContinue | 
Sort-Object LastWriteDate -descending | select -last 1
Write-OutPut $LatestFile
write-output $LatestFile | add-content C:\Scripts\Log.txt
#Copy-Item -path $OriginalDir\$LatestFile $BackupDir\$LatestFile

Testing against Contents in the "M" drive:

List of files

When run from the powershell editor, I get the latest file (20170720 (Thursday).bak). When I run from Windows task scheduler, I get 20170717 (Monday).bak. I'm running from the same account, and am at a loss as to what is going on.

Any ideas?

Larry

  • 1
    LastWriteDate -> LastWriteTime – PetSerAl Jul 21 '17 at 16:23
  • It yields the same result using LastWriteTime (I used that first, but have been grasping at straws trying to get this to work). Thanks! – Larry M Jul 21 '17 at 17:24
  • Is M: a mapped drive? ...or is the scheduled task set to run with highest privileges to include hidden files or vice versa? – Itchydon Jul 21 '17 at 19:42
  • m is a mapped drive. – Larry M Jul 21 '17 at 20:42
  • Might be worth ensuring both M: are mapped to the same place. If they are I would try running the scheduled task with highest privileges, and then running it again but this time not with highest privileges and see if the results are the same – Itchydon Jul 23 '17 at 21:19
1

(For some reason can't access the other account ... original poster here). I checked the mapped drive, it was the same on both. Tried running with different rights, same. Ended up matching on the first 8 characters of the filename (example below):

$filedate = (get-date).AddDays(-1).tostring('MMddyyyy')     
$LatestFile = Get-ChildItem -Path $OriginalDir -Name "$filedate*.bak" | Sort LastWriteTime | Select -First 1

(This worked when run from Task Scheduler and via the PS Editor)

Thanks for all of the help! Still is/was strange behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.