[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Powershell - Scheduled Task with Exchange Remote Session

Posted on 2013-12-12
7
Medium Priority
?
1,197 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 71

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 71

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
New Tabletop Appliances Blow Competitors Away!

WatchGuard’s new T15, T35 and T55 tabletop UTMs provide the highest-performing security inspection in their class, allowing users at small offices, home offices and distributed enterprises to experience blazing-fast Internet speeds without sacrificing enterprise-grade security.

 
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

Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

Question has a verified solution.

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

If something goes wrong with Exchange, your IT resources are in trouble.All Exchange server migration processes are not designed to be identical and though migrating email from on-premises Exchange mailbox to Cloud’s Office 365 is relatively simple…
If you have come across a situation where you need to find some EDB mailbox recovery techniques, then here you will find the same. In this article, we will take you through three techniques using which you will be able to perform EDB recovery. You …
In this Micro Video tutorial you will learn the basics about Database Availability Groups and How to configure one using a live Exchange Server Environment. The video tutorial explains the basics of the Exchange server Database Availability grou…
Screencast - Getting to Know the Pipeline
Suggested Courses

825 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