• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2242
  • Last Modified:

Issue when scheduling a Powershell script

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
namerg
Asked:
namerg
  • 17
  • 12
  • 2
1 Solution
 
GaryCommented:
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
 
namergSystems AdministratorAuthor Commented:
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
 
SubsunCommented:
Make sure you provided correct/exact path for report files in script..
0
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

 
namergSystems AdministratorAuthor Commented:
Subsun, yes, I did...
0
 
GaryCommented:
Are you using system paths? Are these mapped under the svc account
0
 
SubsunCommented:
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
 
namergSystems AdministratorAuthor Commented:
Not using system paths.. I am troubleshooting it right now. Works fine through the command line but not via schedule task. :(
0
 
namergSystems AdministratorAuthor Commented:
Yes. I am at the Script server where we run all the scripts.. No FW, No AV
0
 
namergSystems AdministratorAuthor Commented:
Wow...this is f^%$# weird...have no clue what is going on. Subsun, do you want to see the code?
0
 
SubsunCommented:
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
 
namergSystems AdministratorAuthor Commented:
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
 
SubsunCommented:
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
 
namergSystems AdministratorAuthor Commented:
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
 
SubsunCommented:
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
 
namergSystems AdministratorAuthor Commented:
Subsun, i did point the script to point to a domain controller. But, is not working fine through the schedule task. :(
0
 
namergSystems AdministratorAuthor Commented:
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
 
SubsunCommented:
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
 
namergSystems AdministratorAuthor Commented:
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
 
namergSystems AdministratorAuthor Commented:
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
 
SubsunCommented:
Dumb question but still.. Does the account which you use to run the schedule task has local admin right?
0
 
namergSystems AdministratorAuthor Commented:
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
 
SubsunCommented:
Can you try changing the volume? "C:\scripts\ceridian\" to "D:\scripts\ceridian\"
(or any available volume other than c:\)
0
 
namergSystems AdministratorAuthor Commented:
Nothing :(
I got the email ERROR: dd-mm-yyyy.CSV was not created
0
 
SubsunCommented:
I couldn't find any other reason..After creating folder C:\Windows\SysWOW64\config\systemprofile\Desktop, Did you restart the server?
0
 
namergSystems AdministratorAuthor Commented:
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
 
namergSystems AdministratorAuthor Commented:
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
 
SubsunCommented:
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
 
namergSystems AdministratorAuthor Commented:
Thanks Subsun. UAC is disable and same thing..Let me know what you find...
0
 
SubsunCommented:
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
 
namergSystems AdministratorAuthor Commented:
You got it..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

  • 17
  • 12
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now