2

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
  • Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – Clijsters Apr 19 '18 at 08:26

1 Answers1

0

When you register a job in PowerShell, its created as a Task in Task scheduler under Microsoft\Windows\PowerShell folder. So any actions which requires authentication inside a task will fail with access denied error if the credentials are not explicitly mentioned.

You can test it by having a Try{} Catch{} in your ScriptBlock.

You can achieve your task by using -Credential parameter for Register-ScheduledJob cmdlet. Then the task will use that credential for any opration,

$script_block = {
    param($user_param,$job_name_param)
Try{
    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 -ErrorAction Stop
    $sess > C:\Session.log
    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 
}
Catch{
    $_ > c:\Error.log
}
}

Use above ScriptBlock with and Without -Credetial parameter to Register-ScheduleJob cmdlet. You can see the difference.

Prasoon Karunan V
  • 2,916
  • 2
  • 12
  • 26
  • Code `$sess = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.company.org/PowerShell/ –SessionOption $PSOptions` don't raises any exceptions in job. It returns null without any errors. And I'm already tell that I can pass hardcoded credentials, but don't whant it because password can expire at the moment when job start. When I starts this `$script_block` in Powershell ISE: `Invoke-Command -ScriptBlock $script_block` It works as I expected. And I don't understand why it not works in job, beacuse job is running under my account, not system. – KeyDachable Apr 20 '18 at 05:04
  • You can't see errors because you are not catching it, execute the code I posted via scheduled job and see the result – Prasoon Karunan V Apr 20 '18 at 11:22
  • I'm asure you, I'm wrap my code in try catch as you mentioned, but it throws only when `Import-PSSession` trying to import `$null` – KeyDachable Apr 20 '18 at 12:58
  • yes, and i write it in first post: `I can pass to New-PSSession hardcoded credentials, and in that case it works as I expect` – KeyDachable Apr 20 '18 at 13:46
  • Not for `New-PSSession`, I'm talking about `Register-ScheduledJob` cmdlet with `-Credential` – Prasoon Karunan V Apr 21 '18 at 08:46