Solved

Powershell - Scheduled Task with Exchange Remote Session

Posted on 2013-12-12
7
1,051 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
  • 5
  • 2
7 Comments
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 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 68

Assisted Solution

by:Qlemo
Qlemo earned 500 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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Utilizing an array to gracefully append to a list of EmailAddresses
ADCs have gained traction within the last decade, largely due to increased demand for legacy load balancing appliances to handle more advanced application delivery requirements and improve application performance.
To show how to create a transport rule 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 >> Rules tab.:  To cr…
To show how to generate a certificate request 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 Servers >> Certificates…

758 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now