I have the following script (this is only a part of the entire script):
$FileAge = (Get-Date).AddDays(-90)
$Paths = @("c:\Logs", "c:\inetpub\logs", "c:\Program Files (x86)\Spiceworks\Agent\log", "c:\Deployments")
$ExcludedExtensions = @("SvcTraceViewer.exe", "*DeployLog.xml")
$ExcludedFolders = @()
$Filter = "*.*"
#checking the paths if they exists
$CheckedPaths = {$Paths}.Invoke()
foreach ($Path in $Paths)
{
if((Test-Path $Path) -eq $false)
{
$CheckedPaths.Remove($Path.ToString())
if ($FailedPaths -eq $Null)
{
$FailedPaths = $Path
}
else
{
$FailedPaths = $FailedPaths + "`n$Path"
}
}
}
if ($ExcludedFolders.GetLength(0) -eq 0)
{
$List = Get-ChildItem -Path $CheckedPaths -Recurse -Filter $Filter -Exclude $ExcludedExtensions | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $FileAge}
}
else
{
$List = Get-ChildItem -Path $CheckedPaths -Recurse -Filter $Filter -Exclude $ExcludedExtensions | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $FileAge -and $_.FullName -notmatch $ExcludedFolders}
}
$list | Out-File -filepath "c:\Jobs\LogCleanup\result.txt"
I've setup the script to be run at a specific time via Server 2012 R2 Task Scheduler:
General
- Runas: "domain name\domain user"
- Run whether user logged on or not: x (user is in "log on as a batch job")
- Run with higest privileges: x
Action
- Start a program:
powershell.exe -nologo -file "c:\jobs\logcleanup\logcleanup.ps1"
The "domain name\domain user" has full access to the folder where "result.txt" is written. The same user has modify rights on all the folders it searches through
When the scheduler runs the script, the "result.txt" file is empty.
When I open a powershell window as the "domain name\domain user" (shift+right click on powershell -> run as different user) OR if I run a Runas /user:... command the result.txt file is filled with data.
When opening a powershell prompt as "domain name\domain user" I check with "whoami" to make sure I manually run the script with the same user as the Task Scheduler.
With the command prompt open (where the command was just run with a success), running the task in Task scheduler, results in a filled "result.txt" file.
The same script is also running on several Server 2008 R2 servers without issues. Only on my two Server 2012 R2 servers do I have the above issue.
Thanks in advance for any input :-)