Solved

Issue when scheduling a Powershell script

Posted on 2013-06-24
31
1,881 Views
Last Modified: 2013-07-24
Hello,
I am having a weird behavior when executing a schedule task that executes a powershell script.

I logged in as a Domain Admin, we have an account called script_svc with domain admin rights.

I create the schedule task to be executed by the script_svc domain admin account.
The schedule task executes the script "fine" but with unexpected results.
But if I do Run As on the Powershell Icon and enter the "script_svc" credentials and execute the script manually, run 100% fine with the expected results.

Thoughts ?

Thanks,
0
Comment
Question by:namerg
  • 17
  • 12
  • 2
31 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
executes the script "fine" but with unexpected results
...and the unexpected results are?
If it runs correctly as an Admin user but not as a scheduled task running under an Admin user then probably there is something wrong in your script but you are asking to debug a question.
0
 

Author Comment

by:namerg
Comment Utility
There is nothing wrong with the script. The Powershell gurus from EE contributed a lot :)
The unexpected results is that emails only two attachments: DupClockNumber.csv and NewADUsers.csv and the odd thing is the NewADUsers.csv is empty.

And, the expected results are four attachments:  DupClockNumber.csv, NewADUsers..csv, ExistingCompanyUsers.csv and CSVADMismatch.csv. And these attachments have info.

I have been working on this script for almost a month daily. It runs fine on the console manually.
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Make sure you provided correct/exact path for report files in script..
0
 

Author Comment

by:namerg
Comment Utility
Subsun, yes, I did...
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Are you using system paths? Are these mapped under the svc account
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Are you running the schedule from same computer where you are able to test the script successfully?

Do you have any firewall/AV on computer (Where you schedule the script) which is blocking connection for PowerShell?
0
 

Author Comment

by:namerg
Comment Utility
Not using system paths.. I am troubleshooting it right now. Works fine through the command line but not via schedule task. :(
0
 

Author Comment

by:namerg
Comment Utility
Yes. I am at the Script server where we run all the scripts.. No FW, No AV
0
 

Author Comment

by:namerg
Comment Utility
Wow...this is f^%$# weird...have no clue what is going on. Subsun, do you want to see the code?
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
You can post it and explain how you scheduled the script.. Also did you check if your AV/firewall on the server causing any issue?
0
 

Author Comment

by:namerg
Comment Utility
Thanks subsun for following. This is the script that we have been working together, I put it in production, and I have a feeling that our AD is not replicating well :( Anyway, I will put another question about how to point the LDAP Query in a single domain controller instead doing the LDAP query for the whole domain.
Here it is, the schedule task
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2013-06-24T20:15:40.8357861</Date>
    <Author>COMPANY\DomainAdmin</Author>
  </RegistrationInfo>
  <Triggers>
    <TimeTrigger>
      <StartBoundary>2013-06-24T20:20:00</StartBoundary>
      <Enabled>true</Enabled>
    </TimeTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>UPICOLO\RoseroGA</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>HighestAvailable</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>-command "C:\Scripts\Ceridian\Test_IDMgmt.ps1"</Arguments>
    </Exec>
  </Actions>
</Task>

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Schedule task configuration looks ok to me..
I will put another question about how to point the LDAP Query in a single domain controller instead doing the LDAP query for the whole domain.
Anyways it will be connecting to a domain controller to collect information about the domain. If you have multiple DC's then it will be random connection. If you want to specify a DC to connect then you can..
0
 

Author Comment

by:namerg
Comment Utility
I think I need to point it into another DC, i have to put lots of sleep times so far it worked fine but it broke on
Rename-ADObject : Directory object not found
At C:\scripts\ceridian\Test_IDMgmt.ps1:171 char:7
+             Rename-ADObject -Identity $newdn -NewName $CN
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=williamsp,CN=Users,DC=company,DC=com:ADObject) [Rename-ADObject], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.RenameADObject

Open in new window


I think the the solution for this thread is to point the script into a domain controller instead of the domain which has multiple domain controllers. I did put a question about it.
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Depends.. IMO, If you have a replication problem then you need to fix it... If there is a replication delay then you need to add wait time in script..
0
 

Author Comment

by:namerg
Comment Utility
Subsun, i did point the script to point to a domain controller. But, is not working fine through the schedule task. :(
0
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.

 

Author Comment

by:namerg
Comment Utility
If i go to the command prompt with Run As like the following:
powershell.exe -file  "C:\Scripts\Ceridian\Test_IDMgmt.ps1"
It runs fine, i added the -file into the schedule task and same problem..it does not create the AD users,nothing...how do i echo the schedule task so i can see what is going on ?
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Add -executionpolicy bypass & -noexit as a parameter to powershell.exe, and see if you get any error on console..

For example..
powershell.exe -executionpolicy bypass -noexit -file <script>

Or try directing the output to a txt file by adding >c:\log.txt at the end of command..
0
 

Author Comment

by:namerg
Comment Utility
I did add at the beginning of the script the following:
Start-Transcript -Path "C:\TEMP\Temp.log"
and i got interesting results after executing in it through the schedule task
**********************
Windows PowerShell transcript start
Start time: 20130625120518
Username  : company\companySCRIPT_SVC 
Machine	  : companySCRIPT (Microsoft Windows NT 6.1.7601 Service Pack 1) 
**********************
Transcript started, output file is C:\TEMP\Temp.log
Exception calling "Open" with "1" argument(s): "Microsoft Excel cannot access 
the file 'C:\scripts\ceridian\06-25-2013.xls'. 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 
workbook."
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:36 char:2
+     $objworkbook=$objExcel.Workbooks.Open($CeridianFilePath)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation
 
You cannot call a method on a null-valued expression.
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:37 char:2
+     $objworkbook.SaveAs($savePath,6)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
You cannot call a method on a null-valued expression.
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:38 char:2
+     $objworkbook.Close($false)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
Import-Csv : Could not find file 'C:\scripts\ceridian\06-25-2013.csv'.
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:53 char:2
+     Import-Csv $CSVsavePathFile | ?{$_."Div Descrip" -match 
"Administration"} | sel ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Import-Csv], FileNotFoundExcepti 
   on
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.Im 
   portCsvCommand
 
Compare-Object : Cannot bind argument to parameter 'DifferenceObject' because 
it is null.
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:234 char:21
+     Compare-Object $AD $CSV -property "Last Name","First Name","Job 
Title","Clock N ...
+                        ~~~~
    + CategoryInfo          : InvalidData: (:) [Compare-Object], ParameterBind 
   ingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M 
   icrosoft.PowerShell.Commands.CompareObjectCommand
 
new-object : Exception calling ".ctor" with "1" argument(s): "Could not find 
file 'C:\scripts\ceridian\06-25-2013_ExistingCOMPANYUsersOU_LOG.csv'."
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:290 char:12
+             $att4 = new-object Net.Mail.Attachment($emailattachment4)
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvoca 
   tionException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power 
   Shell.Commands.NewObjectCommand
 
new-object : Exception calling ".ctor" with "1" argument(s): "Could not find 
file 'C:\scripts\ceridian\06-25-2013_CSVADMismatch_LOG.csv'."
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:291 char:12
+             $att5 = new-object Net.Mail.Attachment($emailattachment5)
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvoca 
   tionException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power 
   Shell.Commands.NewObjectCommand
 
Exception calling "Add" with "1" argument(s): "Value cannot be null.
Parameter name: item"
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:300 char:4
+             $msg.Attachments.Add($att4)
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException
 
Exception calling "Add" with "1" argument(s): "Value cannot be null.
Parameter name: item"
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:301 char:4
+             $msg.Attachments.Add($att5)
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException
 
You cannot call a method on a null-valued expression.
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:305 char:4
+             $att4.Dispose()
+             ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
You cannot call a method on a null-valued expression.
At C:\Scripts\Ceridian\Test_IDMgmt.ps1:306 char:4
+             $att5.Dispose()
+             ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
**********************
Windows PowerShell transcript end
End time: 20130625120600
**********************

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
0
 

Author Comment

by:namerg
Comment Utility
Almost there, is not creating the CSV file on this code and i have a win Server 2008 R2 Standard with Excel 2010 instaled. I did create the directory that Subsun suggested on the link and nada..

#Write-Host "BEGIN Convert_XLS_To_CSV Function"
$CSVext = ".csv"
$CeridianFilePath = "C:\scripts\ceridian\" + $CeridianFile + $XLSext
$savePath = "C:\scripts\ceridian\" + $CeridianFile + $CSVext
$objExcel = New-Object -ComObject Excel.Application
$objworkbook=$objExcel.Workbooks.Open($CeridianFilePath)
$objworkbook.SaveAs($savePath,6)
$objworkbook.Close($false)
$objExcel.Quit()
$CSVsavePathFile = $savePath
#Write-Host "END Convert_XLS_To_CSV Function"
return $CSVsavePathFile

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Dumb question but still.. Does the account which you use to run the schedule task has local admin right?
0
 

Author Comment

by:namerg
Comment Utility
Yes sir.
On my client, windows 7 the schedule task runs fine.
Also, I created a check for the csv and is clear is not creating it on the Script Server
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Can you try changing the volume? "C:\scripts\ceridian\" to "D:\scripts\ceridian\"
(or any available volume other than c:\)
0
 

Author Comment

by:namerg
Comment Utility
Nothing :(
I got the email ERROR: dd-mm-yyyy.CSV was not created
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
I couldn't find any other reason..After creating folder C:\Windows\SysWOW64\config\systemprofile\Desktop, Did you restart the server?
0
 

Author Comment

by:namerg
Comment Utility
Rebooted the server and it looks like I have to execute the schedule task with the option "Run only when user is logged on"  Not good. thank you Microsoft. :(
0
 

Author Comment

by:namerg
Comment Utility
I am going to try by logging in locally with a local admin account and execute the powershell script but i do get the following: WARNING: Error initializing default drive: 'The server has rejected the client credentials.'.
PS C:\Users\admin>
Thoughts ?
0
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
I didn't get time to check this on my test box.. I will let you know as soon as I can..

Mean time you can try disabling the UAC on server and see if it makes any change...
0
 

Author Comment

by:namerg
Comment Utility
Thanks Subsun. UAC is disable and same thing..Let me know what you find...
0
 
LVL 40

Accepted Solution

by:
Subsun earned 500 total points
Comment Utility
I just tested this issue..

After creating following folders, it started working for me..
 
C:\Windows\System32\config\systemprofile\Dektop
 
C:\Windows\SysWOW64\config\systemprofile\Desktop
0
 

Author Comment

by:namerg
Comment Utility
You got it..
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Powershell script 9 68
Powershell: Try/Catch help 2 24
VBS Script not working correctly. 1 16
Restore DNS Record 5 40
This script checks a path to see if a folder exists. If the folder does exist you will get output "The folder has previously been created. No action taken" If not it will create the folder. Then adds one user modify permission to the folder. It …
This article will help you understand what HashTables are and how to use them in PowerShell.
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…

744 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

15 Experts available now in Live!

Get 1:1 Help Now