Solved

Powershell Scheduled Task does not run

Posted on 2010-11-16
16
2,178 Views
Last Modified: 2012-06-27
Running the following command to check for new mailboxes created previous day, disable the ActiveSync, IMAP4 and POP3, then enable ActiveSync if they are a member of the SG "ASAllowed". This works fine on its own (without the addPSSnapin and Set Execution policy lines) :-

#Run Daily to disable ActiveSync, POP3 and IMAP4 on all mailboxes created

#previous day on TestDB

#Adding Exchange Snap In to execute Exchange CmdLets in this script
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin

#Set execution policy to allow scripts to be run in Powershell
set-executionpolicy RemoteSigned

get-mailboxdatabase testdb |get-mailbox | Get-User -ResultSize Unlimited | Where

{($_.WhenCreated -gt (get-date).adddays(-1))} | Set-CASMailbox –

ActiveSyncEnabled:$false –POPEnabled:$false -IMAPEnabled:$False

#Run daily to re-enable ActiveSync on ALL mailboxes on TestDB which are members

#of the ASAllowed SG


#Function that enables ActiveSync for members of each group function
function EnableActiveSync { param($enableGroup)

   # Assign all members of the group to a dynamic array
   $allUsers = Get-DistributionGroupMember -Identity $enableGroup
   
   # Loop through the array
   foreach ($member in $allUsers) {

      # Set ActiveSync for each member of the array
      $member | Set-CASMailbox –ActiveSyncEnabled $true
   }
}


#DistributionGroups that allow ActiveSync
EnableActiveSync 'ASAllowed'

I have saved this as ActiveSyncTest.PS1

I have created a batch file (ASTest.bat) with the following line :-

powershell "<path>\ActiveSyncTest.PS1"

Running directly on E2K10 server, schedule the task to run and open ASTask.bat but it simply does not execute - no errors just does not run. It is running under a dom admin account, and has execute at highest level of permissions tick box.

I cannot find any log file as there used to be to check this, but history does not show the task as having run. The task shows the time today it should have run, and it never enters running state.

Anyone any ideas what could be wrong and how to troubleshoot please ?

Thanks
0
Comment
Question by:TheGeezer2010
  • 9
  • 7
16 Comments
 
LVL 27

Accepted Solution

by:
KenMcF earned 200 total points
Comment Utility
It may be haning on this line waiting for a response
Can you comment the line out and test?

set-executionpolicy RemoteSigned

0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
OK so it now runs - it does not do what it says on the tin though !! I have increased this to 200 to investigate why the function does not re-enable ActiveSync on those members of the ASAllowed SG.

Thanks to KenMcF for fixing scheduling part, can I ask Ken why this needs to be omitted when everything I have read says you must include this to allow scripts to run ?

Thanks again
0
 
LVL 27

Assisted Solution

by:KenMcF
KenMcF earned 200 total points
Comment Utility
You only need to set the execution policy once per server unless you need to change it for some reason.
You could also set through a regisrty key instead of through the cmdlet.

http://www.jamssupport.com/KnowledgebaseArticle50027.aspx
0
 
LVL 27

Expert Comment

by:KenMcF
Comment Utility
Can you try to modify your function

function EnableActiveSync { param($enableGroup)

   # Assign all members of the group to a dynamic array
   $allUsers = Get-DistributionGroupMember -Identity $enableGroup
   
   # Loop through the array
   foreach ($member in $allUsers) {

      # Set ActiveSync for each member of the array
      get-casmailbox $member | Set-CASMailbox –ActiveSyncEnabled $true
   }
}
0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
Will try that tomorrow and thanks a million.
0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
OK tried that but it looks as if it cannot accept the get-casmailbox $member - output error is (have replaced AD details with placeholders but the accounts mentioned are all the members of the ASAllowed SG). Looks like not quite right yet ? :-

Cannot process argument transformation on parameter 'Identity'. Cannot convert
the "<domain>/<OU>/<Target_Account>" value of type "Microsoft.Exchange.Data.Directo
ry.Management.ReducedRecipient" to type "Microsoft.Exchange.Configuration.Tasks
.MailboxIdParameter".
    + CategoryInfo          : InvalidData: (:) [Get-CASMailbox], ParameterBind
   in...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-CASMail
   box
0
 
LVL 27

Expert Comment

by:KenMcF
Comment Utility
Try to replace the line with get-casmailbox with one of these

get-casmailbox $member.samaccountname | Set-CASMailbox –ActiveSyncEnabled $true
or
get-casmailbox $member.DistinguishedName | Set-CASMailbox –ActiveSyncEnabled $true

0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
Both complete (although script does not seem to exit) but still do not re-enable the ActiveSync on the account.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 27

Expert Comment

by:KenMcF
Comment Utility
Are you getting any errors?

can you try this for a single account

get-casmailbox USERNAME | Set-CASMailbox –ActiveSyncEnabled $true
0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
Bear in mind that username, SAMAccountName and display name are all the same for the account, this works fine. It also works on UPN. I have tried referencing the $member.upn and again, completes but does not seem to exit the command, and of course, the ActiveSync is still disabled.
0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
OK this is REALLY frustrating now, the code itself runs fine and does what it says, disable all AS, IMAP, POP3 on all accounts in specified DBase, then re-enable AS for all members of the specified group irrespective of when account was created and outputs all mailboxes on specified DBase which have AS enabled- all works great when run interactively :-

#Run Daily to disable ActiveSync, POP3 and IMAP4 on all mailboxes created

#previous day on TestDB

#Adding Exchange Snap In to execute Exchange CmdLets in this script
#Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin

#Set execution policy to allow scripts to be run in Powershell
#set-executionpolicy RemoteSigned

get-mailboxdatabase testdb |get-mailbox | Get-User -ResultSize Unlimited |

Where {($_.WhenCreated -gt (get-date).adddays(-1))} | Set-CASMailbox –

ActiveSyncEnabled:$false –POPEnabled:$false -IMAPEnabled:$False

#Run daily to re-enable ActiveSync on ALL mailboxes on TestDB which are

members #of the ASAllowed SG


#assign members of target DG to array

$allmembers = get-distributiongroupmember -identity asallowed | get-mailbox

#loop through array

foreach ($member in $allmembers) {

#set activesync enabled for each member of the array

$member.Alias | set-CASMailbox -ActiveSyncEnabled:$True

}

#check for enabled members


get-mailboxdatabase testdb | get-mailbox | Get-CASMailbox -resultsize

unlimited | Where-Object {$_.ActiveSyncEnabled -eq "True" } | Select-object

SamAccountName,ActiveSyncEnabled

I have saved this script as ActiveSyncTest.ps1
I have created a batch file (ASTest.bat) which runs following command :-
powershell.exe -command "ActiveSyncTest.ps1"

I schedule this task. Even if I run the task manually I get this spiel :-

The term 'get-mailboxdatabase' is not recognized as the name of a cmdlet, funct
ion, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At C:\BPTest\ActiveSyncTest.PS1:9 char:20
+ get-mailboxdatabase <<<<  testdb |get-mailbox | Get-User -ResultSize Unlimite
d | Where {($_.WhenCreated -gt (get-date).adddays(-1))} | Set-CASMailbox -Activ
eSyncEnabled:$false -POPEnabled:$false -IMAPEnabled:$False
    + CategoryInfo          : ObjectNotFound: (get-mailboxdatabase:String) [],
    CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'get-distributiongroupmember' is not recognized as the name of a cmdle
t, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At C:\BPTest\ActiveSyncTest.PS1:16 char:42
+ $allmembers = get-distributiongroupmember <<<<  -identity asallowed | get-mai
lbox
    + CategoryInfo          : ObjectNotFound: (get-distributiongroupmember:Str
   ing) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'set-CASMailbox' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At C:\BPTest\ActiveSyncTest.PS1:24 char:31
+ $member.Alias | set-CASMailbox <<<<  -ActiveSyncEnabled:$True
    + CategoryInfo          : ObjectNotFound: (set-CASMailbox:String) [], Comm
   andNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'get-mailboxdatabase' is not recognized as the name of a cmdlet, funct
ion, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At C:\BPTest\ActiveSyncTest.PS1:31 char:20
+ get-mailboxdatabase <<<<  testdb | get-mailbox | Get-CASMailbox -resultsize u
nlimited | Where-Object {$_.ActiveSyncEnabled -eq "True" } | Select-object SamA
ccountName,ActiveSyncEnabled
    + CategoryInfo          : ObjectNotFound: (get-mailboxdatabase:String) [],
    CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
This is being run directly on the Exchange mailbox server so what is the problem ?? Why will this thing not run as a scheduled task when called from a bath file but runs fine when invoked interactively ?? Help before I lose my marbles please !!!
0
 
LVL 27

Assisted Solution

by:KenMcF
KenMcF earned 200 total points
Comment Utility
Take a look at this line
#Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin

it should not be commented out.
0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
Hi Ken

If I DON'T comment this line, the script does not run correctly and does not do what it is supposed to do.
0
 
LVL 27

Expert Comment

by:KenMcF
Comment Utility
That command imports the Exchange cmdlets so you are able to run them. What happens to the script when this line line is not commented out?
0
 
LVL 11

Author Comment

by:TheGeezer2010
Comment Utility
It runs interactively perfectly. If I leave it in and run it interactively, the script runs but does nothing.
0
 
LVL 11

Author Closing Comment

by:TheGeezer2010
Comment Utility
I explained at the start that this was Exchange 2010, but the answers I received were for Exchange 2007 - most apply equally, but in this case, the pss module was incorrect.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Disabling the Directory Sync Service Account in Office 365 will stop directory synchronization from working.
Marketers need statistics and metrics like everybody else needs oxygen. In this article we explain how to enable marketing campaign statistics for Microsoft Exchange mail.
In this video we show how to create a Contact 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 Recipients >> Contact ta…
To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…

772 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

10 Experts available now in Live!

Get 1:1 Help Now