I want to write script that enables mail forwarding for some user on exchange server and turn it off at specified time.
But when $script_bloc
executes in job: New-PSSession
returns null without any error.
I can pass to New-PSSession
hardcoded credentials, and in that case it works as I expect, but I don't want to do it because my passwords can expire at the moment when job starts.
Any idea why New-PSSession
doesn't work in a job? And how to make it work?
$user = 'username1'
$fwdto = 'username2'
$remove_date = '19.04.2018 08:33:00'
Set-Mailbox -Identity $user -DeliverToMailboxAndForward $true -ForwardingAddress $fwdto
$job_date=[datetime]::Parse($remove_date)
$job_date=[datetime]::Now.AddSeconds(20) #for test
$trigger = New-JobTrigger -Once -At $job_date
$job_name="rfw_" + $user
$script_block = {
param($user_param,$job_name_param)
Start-Transcript $env:USERPROFILE\jobs\$job_name_param.log -Verbose -Append
$PSOptions = New-PSSessionOption –SkipCACheck –SkipRevocationCheck -SkipCNCheck
$sess = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.company.org/PowerShell/ –SessionOption $PSOptions
Import-PSSession $sess | Out-Default
Set-Mailbox -Identity $user_param -DeliverToMailboxAndForward $false -ForwardingAddress $null | Out-Default
Remove-PSSession $sess | Out-Default
Unregister-ScheduledJob $job_name_param -Force
Stop-Transcript
}
Register-ScheduledJob -Trigger $trigger -Name $job_name -ScriptBlock $script_block -ArgumentList $user, $job_name