Passing Exchange Session to Start-Job

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 3 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
hdsouza1
Posts: 2
Last visit: Sun Nov 28, 2021 1:30 pm

Passing Exchange Session to Start-Job

Post by hdsouza1 »

Hi, I need to start a Job and execute Get-Recipient . I can connect to Exchange, but how do I pass the Exchange session to the Job. Currently it fails on the session.
  1. $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "serv-001/powershell" -Authentication Kerberos
  2. Import-PSSession $Session -AllowClobber -DisableNameChecking
  3. $Job_g = Start-Job -ScriptBlock {Invoke-Command -session $Session  {Get-Recipient r67890}}
  4. Receive-Job  $Job_g
The error on the last (receive) line is "Cannot validate argument on parameter 'Session'. The argument is null or empty."
Thanks
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Passing Exchange Session to Start-Job

Post by jvierra »

The answer is that you can't. A job runs in a s3eparte process and a session is process bound. You must connect separately in the job.
hdsouza1
Posts: 2
Last visit: Sun Nov 28, 2021 1:30 pm

Re: Passing Exchange Session to Start-Job

Post by hdsouza1 »

Hi jvierra,
Thanks for your response.
Ok I tried running as you suggested But now the output of Receive-Job is blank. Where / how do I see the output?
  1. $script = {$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "serv-001/powershell" -Authentication Kerberos;
  2. Import-PSSession $Session -AllowClobber -DisableNameChecking;
  3. Get-Recipient u54427;}
  4. $Job_h = Start-Job -ScriptBlock {Invoke-Command   {$script}}
  5. Receive-Job  $Job_h
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Passing Exchange Session to Start-Job

Post by jvierra »

You also have to detect errors and decide what to do with them.

You cannot use Invoke Command with a job. A job just takes a script block that contains the code to be executed.

help start-job -online - read all of the help until you have a clear idea of how jobs work. You can also search for numerous exampkles of how to use this command.
This topic is 3 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked