Powershell - Scheduled Task with Exchange Remote Session

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).
LVL 1
lunanatAsked:
Who is Participating?
 
QlemoConnect With a Mentor Batchelor, Developer and EE Topic AdvisorCommented:
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
 
lunanatAuthor Commented:
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
 
QlemoConnect With a Mentor Batchelor, Developer and EE Topic AdvisorCommented:
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
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

 
lunanatAuthor Commented:
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
 
lunanatAuthor Commented:
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
 
lunanatAuthor Commented:
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
 
lunanatAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.