Solved

Issue when scheduling a Powershell script

Posted on 2013-06-24
31
2,054 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
[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
  • 17
  • 12
  • 2
31 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39273604
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
ID: 39273630
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
ID: 39274748
Make sure you provided correct/exact path for report files in script..
0
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 

Author Comment

by:namerg
ID: 39274801
Subsun, yes, I did...
0
 
LVL 58

Expert Comment

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

Expert Comment

by:Subsun
ID: 39274832
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
ID: 39274839
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
ID: 39274845
Yes. I am at the Script server where we run all the scripts.. No FW, No AV
0
 

Author Comment

by:namerg
ID: 39275076
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
ID: 39275087
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
ID: 39275293
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
ID: 39275324
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
ID: 39275361
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
ID: 39275387
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
ID: 39275487
Subsun, i did point the script to point to a domain controller. But, is not working fine through the schedule task. :(
0
 

Author Comment

by:namerg
ID: 39275611
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
ID: 39275741
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
ID: 39275743
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
ID: 39275769
0
 

Author Comment

by:namerg
ID: 39275863
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
ID: 39275967
Dumb question but still.. Does the account which you use to run the schedule task has local admin right?
0
 

Author Comment

by:namerg
ID: 39275989
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
ID: 39276043
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
ID: 39276076
Nothing :(
I got the email ERROR: dd-mm-yyyy.CSV was not created
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39276211
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
ID: 39276310
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
ID: 39302022
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
ID: 39307013
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
ID: 39307784
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
ID: 39351720
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
ID: 39352026
You got it..
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

Did you know that more than 4 billion data records have been recorded as lost or stolen since 2013? It was a staggering number brought to our attention during last week’s ManageEngine webinar, where attendees received a comprehensive look at the ma…
In this post we will be converting StringData saved within a text file into a hash table. This can be further used in a PowerShell script for replacing settings that are dynamic in nature from environment to environment.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.
Suggested Courses

623 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