Script runs exponentially slower as scheduled task

I have a script that I've run a few times before using Citrix snapins. It runs just fine in the console, generally taking around 20 minutes. When I try to run it as a scheduled task, it never completes.
The script is as follows:
$time1 = get-date
Add-PSSnapIn Citrix.Common.Commands
Add-PSSnapin Citrix.XenApp.Commands
$_csv = @()
$_csv_header = """Date"",""Sessions"",""IdleSessions"",""ForcedDCSEssions"""
$_csv += $_csv_header
$count = 0
$idlesessions = get-xasession -Full | where {$_.browsername -eq "IDM Search" -and $_.state -ne "Listening" -and $_.state -ne "Disconnected" -and $_.SessionName -ne "Console" -and ($_.currenttime - $_.Lastinputtime).minutes -gt 15}
$sessions = get-xasession -Full | where {$_.browsername -eq "IDM Search" -and $_.state -ne "Listening" -and $_.state -ne "Disconnected" -and $_.SessionName -ne "Console"}
if ($sessions.count -gt 400)
foreach($idlesession in $idlesessions){
stop-xasession -SessionId $idlesession.sessionid -ServerName $idlesession.servername
$count++
$sessioncount = $sessions.count
$idlecount = $idlesessions.count
$date = get-date
$_csv += """$date"",""$sessioncount"",""$idlecount"",""$count"""
$time2 = get-date
$time3 = $time2 - $time1
$duration = $time3.TotalMinutes
$_csv += """$duration"""
$date = get-date -format 'dd.MM.yyyy.hh.mm'
$_csv | out-file c:\powershell\logs\ImageDC$date.csv -Encoding ASCII
The Task Scheduler settings are as follows:
General tab: It runs with local and domain admin privs whether the user is logged in or not
Triggers tab: It begins at 7:55 AM every morning, repeating every 30 minutes for 12 hours (enabled is checked)
Actions tab: Start Program  = %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe      Add arguments = –noninteractive -nologo -noprofile -noexit C:\powershell\ScheduledIDMDisconnect.ps1      start in =  
 c:\powershell
Conditions tab: Only two things checked are "Start the task only if the computer is on AC power" and "Stop if the computer switches to battery power" (those are the defaults, IIRC)
Settings tab: "Allow task to be run on demand" is checked. "Stop the task if it runs longer than (4 hours)" is checked. "If the running task does not end when requested, force it to stop" is checked. "If the task is already
running, then the following rule applies: (Run a new instance in parallel)" is at the bottom.
Can anyone offer any insight? Thanks!
[email protected]

Hi,
Why the -NonInteractive, -NoLogo, -NoProfile, and -NoExit switches? I generally only use -File to point at the script file.
You might also need to check 'Run with highest privileges'.
Don't retire TechNet! -
(Don't give up yet - 13,085+ strong and growing)
I used all those switches because that's what was "in place" as a standard where I am. I already had "run with highest privileges" checked, but switching to just -file + file location seems to have it running as intended now? I'm
at least getting log files in the specified directory.
Thanks!
[email protected]

Similar Messages

  • Run library ThirdParty in Schedule Task - OIM 11

    Hi
    I have a custom code to ScheduleTask, in this code, I need import a external library. In java code I declared the import of library
    I loaded of the .jar to directory OIM_HOME/server/ThirdParty and I ran the UploadJars.sh to ThirdParthy, option 3, but when run the schedule task is diplayed java.lang.NoClassDefFoundError:
    I have to do anymore to run this ThirdParty ?
    Tks

    You need to go into the Weblogic console, select the server (oim_server1) and then the startup tab. Under the classpath box, put in the full path to your jar file. Restart your application server.
    Now your scheduled task will be able to find the jar file.
    -Kevin

  • All kinds of problems with scripts running and slowing things down. It always has to do with "chrome". I sick of it and am going back to IE if I can't get this resolved this weekend.

    What do you want to know.....it's been going on for months and I can't seem to get it resolved. It's definitely a conflict with FF and why you can't resolve it, I have no idea. I've searched the net and these error messages are everywhere. Don't you think it's time you address this.
    At this point I really don't care if I use FF any more. It's slowing everything down on my machine and if you don't have the experience to correct it, then back to IE I'll go.

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.com/kb/Safe+Mode
    *https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes
    Create a new profile as a test to check if your current profile is causing the problems.
    See "Basic Troubleshooting: Make a new profile":
    *https://support.mozilla.com/kb/Basic+Troubleshooting#w_8-make-a-new-profile
    There may be extensions and plugins installed by default in a new profile, so check that in "Tools > Add-ons > Extensions & Plugins" in case there are still problems.
    If that new profile works then you can transfer some files from the old profile to that new profile, but be careful not to copy corrupted files.
    See:
    *http://kb.mozillazine.org/Transferring_data_to_a_new_profile_-_Firefox

  • I'm trying to run a scheduled task as system, but it will not run my powershell script

    I have a powershell script I created that uses credentials within the script to connect to a network resource to copy files every night. It works fine if I just run the script manually. but I need to run this as a scheduled task, preferably as system. I
    have checked "run with highest privileges" still no luck. 
    If I change the user to my account it works fine, but I need it to work without the use of my account. Is this some kind of security policy problem or what would cause this? I figure having the credentials within the script would work, but not so much.
    Paul Arbogast

    I have a powershell script I created that uses credentials within the script to connect to a network resource to copy files every night. It works fine if I just run the script manually. but I need to run this as a scheduled task, preferably as system. I
    have checked "run with highest privileges" still no luck. 
    If I change the user to my account it works fine, but I need it to work without the use of my account. Is this some kind of security policy problem or what would cause this? I figure having the credentials within the script would work, but not so much.
    Paul Arbogast
    Is the Execution Policy set for the script?
    With this information it sounds to be.....
    Take a look @
    http://technet.microsoft.com/en-us/library/ee176961.aspx
    Best Wishes,

  • Opening Excel Workbook Fails when run from Scheduled Task on Windows Server 2008 Rw

    Hi,
    I have a little vbs script that instantiates the Excel.Application object and then opens a work book to perform some tasks on it. The script runs fine when run from the command line. When I attempt to run it as a scheduled task (it is supposed to update
    data that is pulled from a SQL Server at regular intervals), it fails with the following error:
    Microsoft Office Excel cannot access the file 'c:\test\SampleWorkbook.xlsm'. There are several possible reasons: .....
    The file does exist. The path reported in the error is correct. The account under which the task is running is the same account I use to run it from the command line. User Account Control is not enabled, and the task is set up to run with highest privileges.
    When I run the same script through the Task Scheduler from a Windows Server 2003 machine, it works without issue.
    I was just wondering if somebody on this forum has run into a similar issue in connection with Windows Server 2008 R2 and figured out what the magic trick is to make it work. I'm sure it is rights related, but I haven't quite figured out what which rights
    are missing.
    Thanks in advance for any advice you may have.

    This is truly killing me ... trying to get it working on Windows Server 2012 without success.
    I desperately need to automate running Excel macros in a "headless" environment, that is non-interactive, non-GUI, etc.
    I can get it to work using Excel.Application COM, either via VBScript or Powershell, successfully on many other Windows systems  in our environment - Windows Server 2008 R2, Windows 7 (32-bit), etc.,  -BUT-
    The two servers we built out for running our automation process are Windows Server 2012 (SE) - and it just refuses to run on the 2012 servers - it gives the messages below from VBScript and PowerShell, respectively- 
    I have tried uninstalling and re-installing several different versions of Microsoft Excel (2007 Standard, 2010 Standard, 2010 Professional Plus, 32-bit vs. 64-bit, etc.), but it makes no difference.
    Would be extremely grateful if any one out there has had any success in running Excel automation on Server 2012 in a non-interactive environment that they could share.
    ( I have tried adding the "%windir%\syswow64\config\systemprofile\desktop"
    folder, which did fix the issue for me when testing on Windows Server 2008 R2, but sadly did not resolve it on Windows Server 2012 )
    [VBScript error msg]
    Z:\TestExcelMacro.vbs(35, 1) Microsoft Office Excel: Microsoft Office Excel cannot
    access the file 'Z:\TestExcelMacro.xlsm'. There are several possible reasons:
    • The file name or path does not exist.
    • The file is being used by another program.
    • The workbook you are trying to save has the same name as a currently open work
    [Powershell error msg]
    Exception calling "Add" with "0" argument(s): "Microsoft Office Excel cannot open or save any more documents because th
    ere is not enough available memory or disk space.
     To make more memory available, close workbooks or programs you no longer need.
     To free disk space, delete files you no longer need from the disk you are saving to."
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : ComMethodTargetInvocation
    You cannot call a method on a null-valued expression.
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull

  • Exchange 2010 GAL Export script working from EMS but not as a scheduled task

    I have been asked to get a script together to export the GAL on an Exchange 2010 server and then email it to a manager. I have been playing it with days, and have pruned it to the very minimum to at least try and get it working before improving it. At the
    moment I have the text as below:
    Del c:\GALexport.csv
    Get-Recipient -ResultSize unlimited | where {$_.HiddenFromAddressListsEnabled -eq $false} | Select DisplayName,PrimarySMTPAddress,sAMAccountName,alias | Export-Csv "c:\GALexport.csv"
    This works just fine in Exchange Management Shell and deletes the previous report before creating a new one. However, when I set it up as a scheulded task, it does nothing.
    The task is set up as follows:
    Action - Start a Program
    Program/ Script C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe
    Add arguments -version 2.0 -NonInteractive -WindowStyle Hidden -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; d:\Scripts\GalExportReport.ps1"
    This is set to run under my administrator account with the highest privileges and I have the logon as batch right.
    Unfortunately, when I run it as a scheduled task, nothing happens. The last run result is (0x0) and in the history it says 'task completed', but no report is produced. Can anyone advise please?

    Does it delete the c:\GALexport.csv file? If not, then its not even executing the ps1 script...
    - Open cmd prompt and run below command to confirm that there isn't any typo or any other small error...
    C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -version
    2.0 -NonInteractive -WindowStyle Hidden -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; d:\Scripts\GalExportReport.ps1"
    - If above works then something wrong with task scheduler configuration...
    Blog |
    Get Your Exchange Powershell Tip of the Day from here

  • Security Violation Error while running schedule task from OIM.

    Hi All,
    I am getting this error while running a custom java schedule task from OIM:
    *Thor.API.Exceptions.tcAPIException [EJB:010160] Security Violation: User '<anonymous>' has insufficient permission to access EJB:*
    type=<ejb>,application=Xellerate,module=xlDataObjectBeans.jar,ejb=tcReconciliationoperations,method=createDeleteReconciliationEvent
    at Thor.API.Operations.tcReconciliationOperationsClient.createDeleteReconciliationEvent(UnKnown Source).
    I got this error as soon as my code start creating Delete Reconciliation Event.
    Note: I have already protected the JNDI Namespace.
    Please provide some pointers.
    Regards,
    Sunny

    Hi Rajiv,
    Check this:
    package com.centrica.iam.scheduletask;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Hashtable;
    import java.util.Iterator;
    import java.util.Set;
    import oracle.iam.connectors.common.ConnectorLogger;
    import com.thortech.xl.dataaccess.tcDataSet;
    import com.thortech.xl.dataaccess.tcDataSetException;
    import com.thortech.xl.dataobj.PreparedStatementUtil;
    import com.thortech.xl.orb.dataaccess.tcDataAccessException;
    import com.thortech.xl.scheduler.tasks.SchedulerBaseTask;
    import Thor.API.tcResultSet;
    import Thor.API.Exceptions.tcAPIException;
    import Thor.API.Exceptions.tcInvalidValueException;
    import Thor.API.Operations.tcLookupOperationsIntf;
    import Thor.API.Operations.tcReconciliationOperationsIntf;
    import Thor.API.Operations.tcSchedulerOperationsIntf;
    public class CustomFlatFile extends SchedulerBaseTask {
         private static tcSchedulerOperationsIntf schedulerIntf;
         private static tcLookupOperationsIntf lookupIntf;
         private static tcReconciliationOperationsIntf reconIntf;
         String sObjectName;
         String LookupName;
         String LookupName2;
         String FileDirectory;
         String FileName;
         String File;
         String delimeter;
         String isDeleteTrue;
         HashMap<String, String> attrMap = new HashMap();
         HashMap<String, String> delMap = new HashMap();
         HashMap<String, String> finalMap = new HashMap();
         ArrayList list = new ArrayList();
         public boolean isReconStopped;
         public CustomFlatFile()
              isReconStopped = false;
         public void init()
              LookupName = getAttribute("Attribute Lookup Name");
              FileDirectory = getAttribute("Directory Path");
              FileName = getAttribute("File Name");
              delimeter = getAttribute("Delimeter");
              sObjectName = getAttribute("Resource Object Name");
              isDeleteTrue = getAttribute("Is Delete Allowed");
         public void execute(){
              try {
                   System.out.println("Start Exceute");
                   //Initiate lookupIntf
                   lookupIntf = (tcLookupOperationsIntf)getUtility("Thor.API.Operations.tcLookupOperationsIntf");
                   reconIntf=(tcReconciliationOperationsIntf)getUtility("Thor.API.Operations.tcReconciliationOperationsIntf");
                   catch (tcAPIException tcapiexception){
                        tcapiexception.printStackTrace();
                        //logger.error(classname, s, tcapiexception.toString());
                        //logger.setStackTrace(tcapiexception, classname, s, tcapiexception.getMessage());
                   catch (Exception excep){
                        excep.printStackTrace();
                        //logger.error(classname, s, excep.toString());
                        //logger.setStackTrace(excep, classname, s, excep.getMessage());
                   attrMap = readLookup(LookupName);
                   System.out.println(attrMap.toString());
                   readFile();
                   if (isDeleteTrue.equalsIgnoreCase("true"))
                        performDelete();
                   System.out.println("Finish Execute");
         public void performDelete()
              System.out.println("Start Perform delete");
              int k = list.size();
              System.out.println("list size " + list.size());
              try
                   Thread.sleep(15000);
         /*     Hashtable ahashtable[] = new Hashtable[k];
              Hashtable hashtable = new Hashtable();
              for (int i=0;i<k;i++)
                   hashtable.put("User Id", list.get(i));
                   ahashtable[i] = hashtable;
                   System.out.println(list.get(i));
              Set set = reconIntf.provideDeletionDetectionData(sObjectName, ahashtable);
              System.out.println("Set--" + set.toString());
              tcResultSet tcresultset = reconIntf.getMissingAccounts(sObjectName, set);
              System.out.println("tcresultset - " + tcresultset.getRowCount());
              if (!(tcresultset.isEmpty()))
                   long l[] = reconIntf.deleteDetectedAccounts(tcresultset);
                   for (int i1=0;i1<l.length;i1++)
                        System.out.println("delete recon key " + l[i1]);
              //Get the existing list of Managed users
                   tcDataSet tcdataset = new tcDataSet();
                   tcDataSet tcdataset1 = new tcDataSet();
                   String query = "select orf.orf_fieldname,prf.prf_columnname, sdk.sdk_name from orf, sdk, pkg, tos, prf, obj " +
                             "where pkg.obj_key = obj.obj_key and pkg.pkg_key = tos.pkg_key and tos.sdk_key is not null " +
                             "and tos.sdk_key=sdk.sdk_key and tos.tos_key=prf.tos_key and prf.prf_iskey='1' and prf.orf_key=orf.orf_key " +
                             "and orf.orf_parent_orf_key is null and obj.obj_name='" + sObjectName + "'";
                   tcdataset.setQuery(getDataBase(), query);
                   tcdataset.executeQuery();
                   String FFName = tcdataset.getString("prf_columnname");
                   String FName = tcdataset.getString("sdk_name");
                   String ROFName = tcdataset.getString("orf_fieldname");
                   System.out.println("form- " + FName + " Field- " + FFName);
                   query = "select " + FFName + " from " + FName + " udtable, oiu a, ost b " +
                             "where udtable.orc_key=a.orc_key and a.ost_key=b.ost_key and b.ost_status!='Revoked'";
                   System.out.println(query);
                   tcdataset1.setQuery(getDataBase(), query);
                   tcdataset1.executeQuery();
                   int i = tcdataset1.getRowCount();
                   ArrayList list1 = new ArrayList();
                   String s1 = null;
                   System.out.println("N. of rows--" + i);
                   for (int j=0;j<i;j++)
                        tcdataset1.goToRow(j);
                        s1 = tcdataset1.getString(0);
                        System.out.println("s1---" + s1);
                        if (!(list.contains(s1)))
                             list1.add(s1);
                             System.out.println("under if--" + s1);
                   //Getting the existing list of unmanaged users
                   query = "select distinct (b.rcd_value) from rce a, rcd b, orf c, obj d where a.rce_key=b.rce_key and " +
                             "b.orf_key=c.orf_key and c.orf_fieldname='" + ROFName + "' and a.rce_status!='Event Linked' " +
                                       "and a.obj_key = d.obj_key and d.obj_name='" + sObjectName + "'";
                   tcdataset1.setQuery(getDataBase(), query);
                   tcdataset1.executeQuery();
                   i = tcdataset1.getRowCount();
                   System.out.println("No. Of Unmanaged Users " + i);
                   for (int j=0;j<i;j++)
                        tcdataset1.goToRow(j);
                        s1 = tcdataset1.getString(0);
                        System.out.println("s1---" + s1);
                        if (!(list.contains(s1)))
                             list1.add(s1);
                             System.out.println("under if--" + s1);
                   int k1 = list1.size();
                   System.out.println("list1 size--" + k1);
                   for (int j1=0;j1<k1;j1++)
                        delMap.clear();
                        delMap.put(ROFName, (String)list1.get(j1));
                        System.out.println(delMap.toString());
                        long l = reconIntf.createDeleteReconciliationEvent(sObjectName, delMap);
                        System.out.println("delete recon key--- " + l);
              catch (Exception exception)
                   exception.printStackTrace();
         public void readFile(){
              String s = "readFile()";
              //logger.setMethodStartLog(classname, s);
              HashMap map = new HashMap();
              try {
              File = getFile();
              BufferedReader reader = new BufferedReader(new FileReader(new
                        File(File)));
              String line = "";
              int k = attrMap.size();
              String value[] = new String[k];
              String Header[]= new String[k];
              if (delimeter.equalsIgnoreCase("|"))
                   delimeter = "\\" + delimeter;
                   line = reader.readLine();
                   Header = line.split(delimeter);
                   while((line = reader.readLine()) != null)
                        value = line.split(delimeter);
                        k = value.length;
                        for (int i = 0;i<k;i++){
                             finalMap.put(attrMap.get(Header), value[i]);
                        System.out.println(finalMap.toString());
                        System.out.println("Start Ignoring Event");
                        if (!(reconIntf.ignoreEvent(sObjectName, finalMap)))
                             System.out.println("Not Ignored");
                        long l1 = reconIntf.createReconciliationEvent(sObjectName, finalMap, true);
                        System.out.println("Recon Key--" + l1);
                        else
                             System.out.println("ignore event ---" + finalMap.toString());
                        list.add(finalMap.get("User Id"));
                        System.out.println(list.size() + "add--" +finalMap.get("User Id") );
                        finalMap.clear();
              catch (Exception exception)
                   exception.printStackTrace();
         public boolean stop(){
              String s = "stop()";
              //logger.setMethodStartLog(classname, s);
              //logger.info(classname, s, "Stopping Reconciliation........");
              isReconStopped = true;
              //logger.setMethodFinishLog(classname, s);
              return true;
         FileFilter fileFilter = new FileFilter()
         public boolean accept(File file)
         String sFilePath = file.getName();
         if( sFilePath.startsWith(FileName) )
         return true;
         else
         return false;
         public String getFile() throws FileNotFoundException, Exception{
              String s = "getFile()";
              //logger.setMethodStartLog(classname, s);
              String s1;
              File dir =     new File(FileDirectory);
              File[] files = dir.listFiles(fileFilter);
              if (files.length ==0)
                   throw new FileNotFoundException();
              if (files.length>1)
                   throw new Exception("Multiple Matches found for this file name");
              s1 = files[0].toString();
              //logger.setMethodFinishLog(classname, s);
              return s1;
         public HashMap readLookup(String s1){
              String s = "readLookup()";
              //logger.setMethodStartLog(classname, s);
              HashMap map = new HashMap();
              try {
              tcResultSet tc1=     lookupIntf.getLookupValues(s1);
              int i = tc1.getRowCount();
              for (int j = 0;j<i;j++){
                   tc1.goToRow(j);
                   map.put(tc1.getStringValue("Lookup Definition.Lookup Code Information.Code Key"), tc1.getStringValue("Lookup Definition.Lookup Code Information.Decode"));
              catch (tcAPIException tcapiexception){
                   tcapiexception.printStackTrace();
                   //logger.error(classname, s, tcapiexception.toString());
                   //logger.setStackTrace(tcapiexception, classname, s, tcapiexception.getMessage());
              catch (Exception excep){
                   excep.printStackTrace();
                   //logger.error(classname, s, excep.toString());
                   //logger.setStackTrace(excep, classname, s, excep.getMessage());
              return map;

  • Variable text is blank in emails when using Scheduled Task to email event log notifications

    I am trying to use powershell to email notification when a user account gets locked.  I am running the script from a server 2008 domain controller.
    I have tried multiple scripts and I have the same issue every time.  The script works fine when I run it directly from the powershell command line window.
    However whenever I try running the exact same scripts from an event-triggered scheduled task, the script runs, however any content that generated from a variable is not added to the email.  It is just left blank and ignored.
    I have tried adding lots of permissions including domain administrator group membership to the account  runs the task from and it doesn't include all the expected text unless I run it from the built-in domain administrator account.
    The task runs and the email is sent, but the email is missing all the content generated by variables.
    How can this be fixed?
    Here is an example script.
    $AccountLockOutEvent = Get-EventLog -LogName "Security" -InstanceID 4740 -Newest 1
    $LockedAccount = $($AccountLockOutEvent.ReplacementStrings[0])
    $AccountLockOutEventTime = $AccountLockOutEvent.TimeGenerated
    $AccountLockOutEventMessage = $AccountLockOutEvent.Message
    $messageParameters = @{ 
    Subject = "Account Locked Out: $LockedAccount" 
    Body = "Account $LockedAccount was locked out on $AccountLockOutEventTime.`n`nEvent Details:`n`n$AccountLockOutEventMessage"
    From = "[email protected]
    To = "[email protected]
    SmtpServer = "exch2010.domain.local" 
    Send-MailMessage @messageParameters
    =================================================
    Here is an example of task settings.
    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
      <RegistrationInfo>
        <Date>2015-03-25T21:40:28.8095226</Date>
        <Author>DOMAIN\administrator</Author>
      </RegistrationInfo>
      <Triggers>
        <EventTrigger>
          <Enabled>true</Enabled>
          <Subscription>&lt;QueryList&gt;&lt;Query Id="0" Path="Security"&gt;&lt;Select Path="Security"&gt;*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and EventID=4740]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
        </EventTrigger>
      </Triggers>
      <Principals>
        <Principal id="Author">
          <UserId>DOMAIN\WilliamsD</UserId>
          <LogonType>Password</LogonType>
          <RunLevel>LeastPrivilege</RunLevel>
        </Principal>
      </Principals>
      <Settings>
        <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
        <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
        <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
        <AllowHardTerminate>true</AllowHardTerminate>
        <StartWhenAvailable>false</StartWhenAvailable>
        <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
        <IdleSettings>
          <StopOnIdleEnd>true</StopOnIdleEnd>
          <RestartOnIdle>false</RestartOnIdle>
        </IdleSettings>
        <AllowStartOnDemand>true</AllowStartOnDemand>
        <Enabled>true</Enabled>
        <Hidden>false</Hidden>
        <RunOnlyIfIdle>false</RunOnlyIfIdle>
        <WakeToRun>false</WakeToRun>
        <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
        <Priority>7</Priority>
      </Settings>
      <Actions Context="Author">
        <Exec>
          <Command>powershell.exe</Command>
          <Arguments>-nologo -File "C:\powershell\l2.ps1"</Arguments>
        </Exec>
      </Actions>
    </Task>

    By variable text I mean everything that it generates by using a variable such as the user's name ($LockedAccount)
    and everything else such as $AccountLockOutEventTime and everything else that is generated from
    a variable.
    Nothing like that appears in the email only hard coded text.
    I am not running it remotely.  I am logged directly onto the domain controller and I tried giving
    the account that is used to run the task more and more permissions including domain administrator group membership with the same result.
    When I run the exact same script on the same domain controller locally via the powershell CLI all of the info appears.
    This is the info when the email is generated by running the script directly from the powershell CLI:
    ================================================
    ================================================
    Account BondJ was locked out on 03/26/2015 20:42:18.
    Event Details:
    A user account was locked out.
    Subject:
                    Security ID:                         S-1-5-18
                    Account Name:                 DC1$
                    Account Domain:                            
    DOMAIN
                    Logon ID:                            
    0x3e7
    Account That Was Locked Out:
                    Security ID:                         S-1-5-21-3440879815-2193117124-1719501250-1154
                    Account Name:                 BondJ
    Additional Information:
                    Caller Computer Name:                DC1
    ===================================================
    ====================================================
    Below is the contents of the email when the same script runs via scheduled task trigger using any account I try other than the built-in domain Administrator account.
    =======================================================
    ======================================================
    Account  was locked out on .
    Event Details:
    ===================================================
    Just mostly blank email body with the info above.  All the important information text is missing from the email.

  • SCCM 2007 query to find Scheduled tasks setup on a client.

    Hello all,
    I have been asked by senior management at the school where i work to automate the shutdown of PCs at a specific time each night.
    So I created a batch script that sets up a scheduled task on the clients to do this, and rolled it out via software distribution.
    How would I go about creating a query to check which machines do not have the scheduled task?

    We are needing to change passwords on ALL our Service Accounts.  Was able to pull out the services being started by a Service Account, but...also need to look for scheduled tasks run by Service Accounts...that link you sent doesn't seem to show the
    Run As name?
    Thanks.

  • Can scheduled tasks be set up using a Java Object?

    I need to run a script that will create a scheduled task in
    the Coldfusion Administrator CF8. I have used a Java Object to
    register a custom tag and I am wondering if you can do the same
    thing with a scheduled task.

    No special java class/object is needed actually. ColdFusion
    offers a built-in tag for this, <cfschedule>.
    Read more here:
    http://livedocs.adobe.com/coldfusion/8/Tags_r-s_11.html

  • How to handle timestamp in custom scheduled task written for Target Recon

    Hi,
    I have wriiten a Custom scheduled task to reconciile users from target system..but whenever I run the Target Recon Scheduled task .. it generates the Recon. events for all users.
    How to handle this.. how to pass Timestamp value to custom Target Recon scheduled task.
    Thanks,
    Pallavi

    To add to Kevin's point -
    You will have to have a attribute either in the IT Resource or the Schedule Task. At the begining of the reconciliation searches, get the timestamp of the target system and store it in a variable. Fectch the timestamp attribute value from the IT Resource/Schedule Task and use that value as one of the search criteria of user profiles on the target.
    Once all the user profiles from the target are queried and reconciliation is completed then update either the IT Resource or Schedule Task attribute using OIM API.
    Hope this helps :)

  • CF 9 Upgrade process Ran All Scheduled Tasks

    I just completed the upgrade process from CF8 Enterprise to CF9 Enterprise on our test system, Windows 2003 R2P2 using IIS6 and SQL Server 2000.  I have no schedule tasks with an active schedule, but the upgrade process ran all of the tasks.  Running all of the scheduled tasks created 200+ e-mails.
    Any ideas on what happened?  I ran the coldfusion_9_wwe_win.exe and installed the CF9 ODBC and CF9 SOIR services.
    If this happened on my TEST system (with no actively scheduled tasks) what's going to happen when I upgrade my production system?
    Thanks in advance for your time.
    Libby

    I can't answer your specific question (*), but I would seriously reconsider your approach of UPGRADING a CF server.  Set up CF9 in parallel, and migrate the application/website across to it.
    If you do an inline upgrade and it fails: you've got nothing to fall back on.  If you to a "cross-grade", your working CF8 instance is still there as a fail-over, if anything goes wrong with the CF9 install.
    Adam
    (*) you might want to raise a bug report, though.

  • How can I Backup scheduled tasks in ARD?

    Hi,
    I run a number of scheduled tasks throughout the day and I am wondering how I copy these so that I can protect them?
    Thanks.
    Message was edited by: Host <to clarify Subject>

    Saved tasks are in the com.apple.RemoteDesktop.plist file. Back that up and you should be fine.
    Regards.

  • How can I setup a scheduled task to run a Powershell Script delivered as a Group Policy Preference

    I have a Powershell script I want to run only once when a user logs onto their system. This script would move all the PST files from the Local drive and the Home drive to a folder location within the users profile. I wanted to run this as a Windows 7 Scheduled Task using Group Policy Preferences. How can I get this to happen short of a logon script? I have updated all the machines to WMF 4.0 so could I use a Scheduled Job instead? I wanted to run the script as the logon user but elevated.#Start Outlook and Disconnect attached PST files.
    $Outlook = New-Object -ComObject Outlook.Application
    $namespace = $outlook.getnamespace("MAPI")
    $folder = $namespace.GetDefaultFolder("olFolderInbox")
    $explorer = $folder.GetExplorer()
    $explorer.Display()
    $myArray= @()
    $outlook.Session.Stores | where{ ($_.FilePath -like'*.PST') } | foreach{[array]$myArray+= $_.FilePath}
    for
    ($x=0;$x-le$myArray.length-1;$x++)
    $PSTPath= $myArray[$x]
    $PST= $namespace.Stores | ?{$_.FilePath -like$PSTPath}
    $PSTRoot= $PST.GetRootFolder() #Get Root Folder name of PST
    $PSTFolder= $Namespace.Folders.Item($PSTRoot.Name) #Bind to PST for disconnection
    $Namespace.GetType().InvokeMember('RemoveStore',[System.Reflection.BindingFlags]::InvokeMethod,$null,$Namespace,($PSTFolder)) #Disconnect .PST
    #Move All PST files to the default location while deleting the PST files from their original location.
    $SourceList = ("$env:SystemDrive", "$env:HOMEDRIVE")
    $Destination = ("$env:USERPROFILE\MyOutlookFiles")
    (Get-ChildItem -Path $SourceList -Recurse -Filter *.PST) | Move-Item -Destination $Destination
    #Attach all PST files from the default location.
    Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
    $outlook = new-object -comobject outlook.application
    $namespace = $outlook.GetNameSpace("MAPI")
    dir “$env:USERPROFILE\MyOutlookFiles\*.pst” | % { $namespace.AddStore($_.FullName) }

    Mike,
    I do not understand what appears to be a regular expression above. I did add the PowerShell script to the HKCU RunOnce Key as suggested.
    Windows Registry Editor Version 5.00
    C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -noprofile -sta -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File "C:\scripts\Windows PowerShell\Move-PST.ps1"
     I'm delivering this using Group Policy Preferences. It seems to fail or time out when run because the behavior is different if I run the script from within the PowerShell IDE. I added the parameters to the script and will try it again in the morning.

  • Unable to Configure a PowerShell Script to Run as a Scheduled Task

    Hi ,
    I have a powershell script from Dieters blog http://scug.be/dieter/2011/07/06/scom-2007-how-to-backup-your-unsealed-management-packs/#comment-1058 which backups the unsealed management packs in SCOM. I am able to run the script successfully in the powershell
    prompt but when i schedule it as a task it fails with an error code 1.
    "Task Scheduler successfully completed task "\Backup Unsealed Management Pack" , instance "{xxxxxxxxxxxxxxxxxxxxxxxxxxxx}" , action "Powershell.exe" with return
    code 1."
    I am running the task using the highest privilages and have tried bypassing the script using and have configured the script as per http://www.metalogix.com/help/Content%20Matrix%20Console/SharePoint%20Edition/002_HowTo/004_SharePointActions/012_SchedulingPowerShell.htm
    -ExecutionPolicy Bypass c:\scripts\myscript.ps1
    Still i am unable to run the task without errors. Kindly assist.
    Jesty

    Hi Jesty,
    Please make sure you have followed these steps to schedule a powershell script task:
    1.  Save the powershell script as .ps1 in local computer.
    2.  Right click the .ps1 file and run with powershell and check if the script can run successfully.
    3.  schedule task->action:Start a program->Program/script:powershell.exe->Add argument:-ExecutionPolicy Bypass c:\scripts\myscript.ps1
    Best Regards,
    Anna

Maybe you are looking for