exchange commands in scheduled tasks not working

Lotfi BOUCHERIT 91 Reputation points
2021-01-08T06:24:37.937+00:00

hello,
i have the bellow script that run some audit commands that needs to be run in a scheduled task for automation purposes. if i try to run it directly, it works without any problem, but if i try to run it in a scheduled task, it does nothing.
Could you please, help me or tell me what i shoud do?
thank you in advance.
#########username############
$username = "admin@keyman .local"
$logfile = "L:\Script-AuditLog\adminmailbox.log"

#########date today##########  
$dt = Get-Date -UFormat "%d%m%Y"  
$namecsv = "L:\Script-AuditLog\Results\adminmailbox-"+$dt+".csv"  
$namehtml = "adminmailbox-"+$dt+".html"  
echo "$dt : script settings retrieved" >> $logfile  
  
#########password############  
#echo "$dt : audit started" >> $logfile  
$encrypted = Get-Content L:\Script-AuditLog\Password.txt | ConvertTo-SecureString  
$UserCredential = New-Object System.Management.Automation.PsCredential($username, $encrypted)  
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exc.domain.local/PowerShell/ -Authentication Kerberos -Credential $UserCredential  
  
Import-PSSession $Session -DisableNameChecking  
  
############audit############  
echo "$dt : script executed" >> $logfile  
  
#pour exporter csv  
Search-AdminAuditLog | where-object {($_.cmdletname -eq 'Add-Mailboxpermission') -or ($_.cmdletname -eq 'Add-AdPermission')} | .\Get-SimpleAuditLogReport.ps1 -agree | export-csv $namecsv -delimiter ';'  
#############################  
  
Remove-PSSession $Session  
Exchange Server Management
Exchange Server Management
Exchange Server: A family of Microsoft client/server messaging and collaboration software.Management: The act or process of organizing, handling, directing or controlling something.
7,390 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,408 questions
{count} votes