Solved

Powershell - Scheduled Task with Exchange Remote Session

Posted on 2013-12-12
7
1,126 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 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 70

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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
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

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
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…
This video discusses moving either the default database or any database to a new volume.

705 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