?
Solved

Powershell - Scheduled Task with Exchange Remote Session

Posted on 2013-12-12
7
Medium Priority
?
1,157 Views
Last Modified: 2013-12-13
I'm writing a powershell script which will be supplied with an AD username, and a number of days.

With that information, it will:
1) identify the AD-specified manager of that user
2) Send an email to the user, the manager, and the helpdesk with relevant information
3) schedule a command (on the LOCAL computer, since credentials are needed) to remove-mailbox on the exchange server at the current date + the user-specified number of days.

It does a LOT of other things too, but those are irrelevant to this question.  That other functionality has been tested and is successful.

The problem that I'm having is that although manually running the command shows a successful completion, it's not doing what it's supposed to do.  I suspect it is at least in part due to variable expansion of things such as $validatedTerminatedUsername.SamAccountName, but I wanted to see if anyone else had any other gotchas in mind.

$JobName = "Delete_$($validatedTerminatedUserName.SamAccountName)_$($TargetDate.Year)$($TargetDate.Month)$($TargetDate.Day)"

Write-Verbose -message "Generating Scheduled task $($JobName)"
$JobTrigger = New-JobTrigger -once -at $TargetDate
$Job = Register-ScheduledJob -Name $JobName `
	-scriptblock {powershell.exe $ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeserver.domain.com/PowerShell ; Import-PSSession $ExchangeSession ; Remove-Mailbox $validatedTerminatedUserName.SamAccountName } `
	-Trigger $JobTrigger

Open in new window


As of yet I have not created the job options, so it's not set to run only while logged in (and other things that are specified within the joboptions).
0
Comment
Question by:lunanat
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
7 Comments
 
LVL 70

Accepted Solution

by:
Qlemo earned 2000 total points
ID: 39715479
Correct. I reckon your scheduled task is registered (created) correctly, but on execution does not remove the mailbox? $validatedTerminatedUserName is no longer valid in the script block, so you'll have to provide it as parameter to the script. (I've done a change to how the jobname is built, too, and I don't think you need to call PS explicit):
$JobName = "Delete_$($validatedTerminatedUserName.SamAccountName)_$(get-date $TargetDate -format 'yyyymmdd')"

Write-Verbose -message "Generating Scheduled task $JobName"
$JobTrigger = New-JobTrigger -once -at $TargetDate
$Job = Register-ScheduledJob -Name $JobName `
	-scriptblock {
                param($user)
                $ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeserver.domain.com/PowerShell
                Import-PSSession $ExchangeSession
                Remove-Mailbox $user } -ArgumentList $validatedTerminatedUserName.SamAccountName `
	-Trigger $JobTrigger

Open in new window

0
 
LVL 1

Author Comment

by:lunanat
ID: 39717201
Hmm... no luck.  I added some text file logging to try and shed some light, and instead I only have more questions.

Write-Verbose -message "Generating Scheduled task $($JobName)"
		$JobTrigger = New-JobTrigger -once -at $TargetDate
		$JobOptions = new-ScheduledJobOption -RequireNetwork
		$Job = Register-ScheduledJob -Name $JobName `
			-scriptblock {
					param($user)
					add-content C:\\temp\\test.log "Beginning Log: $(Get-Date)"
					$user | add-content C:\\temp\\test.log
					Get-Module | add-content C:\\temp\\test.log
					$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://email.domain.com/PowerShell
					Import-PSSession $ExchangeSession | add-content C:\\temp\\test.log
					$ExchangeSession | add-content C:\\temp\\test.log
					Remove-Mailbox $user | add-content C:\\temp\\test.log
					add-Content C:\\temp\\test.log "Ending Log: $(Get-Date)"
			} -ArgumentList $validatedTerminatedUserName.SamAccountName `
			-Trigger $JobTrigger `
			-ScheduledJobOption $JobOptions

Open in new window


My log file SHOULD produce something as follows:

Beginning Log: <date>
testuser
< potentially some irrelevant modules>
tmp_mfvkqckx.lhu  <this is the exchange imported stuff>
[PSSession] Session1
<mailbox removal output>
Ending Log: <date>

However instead, all I get is:
Beginning Log: 12/13/2013 09:27:57
testuser
Ending Log: 12/13/2013 09:27:57

Suspecting that that is was a credential issue, I added this line:

Get-Credential | add-content C:\\temp\\test.log

However that just made the task run indefinitely.
0
 
LVL 70

Assisted Solution

by:Qlemo
Qlemo earned 2000 total points
ID: 39717286
Get-Credential prompts for credentials, so that does not work at all for your purpose of logging.
You don't use \\, just \, for paths.
Not all cmdlets produce output on success, so don't be confused if you do not anything just by piping their results to a file.

A better way to do what you try is to use Start-Transcript at the beginning and Stop-Transcript at the end of the script. That collects all output which would be put into the console window usually into a file. You also might want to dump $error as last output, to see if any error has been recorded. ($error contains the last n errors, with the most recent on top.)
0
Office 365 Training for Admins - 7 Day Trial

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

 
LVL 1

Author Comment

by:lunanat
ID: 39717326
Ah, that makes more sense about the running-forever problem.

When using non-escaped backslashes, I was not able to produce any logfile output.

The same, oddly, was true of transcripts.  Running the transcript manually, I was able to produce a good-looking log file.  Running it within the task scriptblock, it didn't even show the start/end tags.
0
 
LVL 1

Author Comment

by:lunanat
ID: 39717494
Aha... I started looking in the pre-existing log files, and I came up with a very useful tidbit.  Going to post this now before I start experimenting further, in case anyone is presently testing powershell code.


<ToString>@{Exception=System.Management.Automation.RemoteException: Connecting to remote server email.domain.com failed with the following error message : A specified logon session does not exist. It may already have been terminated. For more information, see the about_Remote_Troubleshooting Help topic.;

Going to hard-code the credentials and see what happens.
0
 
LVL 1

Author Comment

by:lunanat
ID: 39717621
Nailed it.

		Write-Verbose -message "Generating Scheduled task $($JobName)"
		$JobTrigger = New-JobTrigger -once -at $TargetDate
		$JobOptions = new-ScheduledJobOption -RequireNetwork
		$Password = Read-Host -AsSecureString "Enter your password, for the scheduled task"
		$creds = new-object -typename System.Management.Automation.PSCredential -ArgumentList $env:UserName, $Password
		$Job = Register-ScheduledJob -Name $JobName `
			-scriptblock {
					param($user)
					add-content C:\\temp\\test.log "Beginning Log: $(Get-Date)"
					add-content C:\\temp\\test.log "Targetted User: $($user)"
					add-content C:\\temp\\test.log "Running Username: $($env:UserName)"
					Get-Module | add-content C:\\temp\\test.log
					$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://email.domain.com/PowerShell
					Import-PSSession $ExchangeSession | add-content C:\\temp\\test.log
					$ExchangeSession | add-content C:\\temp\\test.log
					Remove-Mailbox $user -confirm:$false | add-content C:\\temp\\test.log
					add-Content C:\\temp\\test.log "Ending Log: $(Get-Date)"
			} -ArgumentList ($validatedTerminatedUserName.SamAccountName) `
			-Trigger $JobTrigger `
			-ScheduledJobOption $JobOptions `
			-Credential $creds

Open in new window

0
 
LVL 1

Author Closing Comment

by:lunanat
ID: 39717624
Last bit of code provided works beautifully.

I'll need to test, and I know it'll break if the stored password becomes invalid due to a user changing their password, but that's of minor concern.  For the time-being, when I manually run the task, it does everything it is meant to do.
0

Featured Post

Office 365 Training for Admins - 7 Day Trial

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In previous parts of this Nano Server deployment series, we learned how to create, deploy and configure Nano Server as a Hyper-V host. In this part, we will look for a clustering option. We will create a Hyper-V cluster of 3 Nano Server host nodes w…
Check out this step-by-step guide for using the newly updated Experts Exchange mobile app—released on May 30.
In this video we show how to create an email address policy in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.:  First we need to log into the Exchange Admin Center. Navigate to the Mail Flow…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question