Solved

Issue when scheduling a Powershell script

Posted on 2013-06-24
31
1,928 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
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
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 

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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

In this article, we will see the basic design consideration while designing a Multi-tenant web application in a simple manner. Though, many frameworks are available in the market to develop a multi - tenant application, but do they provide data, cod…
A brief introduction to what I consider to be the best editor for 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…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

776 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