October 18, 2015 at 4:32 pm #31000
I wondering if anyone can point me in the right direction with some strange behavior that I'm experiencing. I have the following code:
$myService = "bits"
$currentDateTime = Get-Date
$serviceState = (Get-WmiObject -Class win32_service -Filter "name='$myService'").State
$logInfo = "$currentDateTime – The $myService service is currently $serviceState"
Add-Content -Path $workingDirectory -Value $logInfo
This code was first tested in a script on my machine which is running Windows 7 64-bit PS 4 with the following results in the log file:
`10/18/2015 12:20:16 – The bits service is currently Running`
but when I run the script on the server which is running Windows Server 2008 64bit PS 2 I get the following log results:
`10/18/2015 19:51:04 – The bits service is currently`
The script is being ran from Task Manager. However, I can successfully retrieve the state of the bits service from the PS command window. My script depends on getting the state of the service. I've tried getting the status value as well on the server and nothing.Note: bits was just used in my testing. Any help on things to try would be great? By the way, the executionpolicy on the machine is set to RemoteSigned for the currentuser which is also the user that's running the scheduled task.
Last thing, I can execute the powershell script from the command window and the script runs just fine printing the state. However, calling it from a scheduled task does not print the state in the file.
October 19, 2015 at 4:58 am #31020
If you are using PS version 2 on some machines, you will want to alter your script slightly:
$myService = "bits" $currentDateTime = Get-Date $serviceState = Get-WmiObject -Class win32_service -Filter "name='$myService'" | select -expandproperty State $logInfo = "$currentDateTime – The $myService service is currently $serviceState" Add-Content -Path $workingDirectory -Value $logInfo
October 19, 2015 at 6:00 am #31024
Steven Ayers thanks for the suggestion; I'll take a look into doing that. However, did find the answer to my issue. The problem was that I had to run the task with "Run with highest privileges" checked. Found out also that all the other small powershell scripts that we had was doing simple task like emailing and running from a batch file did not have to have this option checked. I'm assuming since my script was querying the system then this had to be checked.
October 19, 2015 at 6:10 am #31025
No worries – I do want to say, unless you are working on updated PowerShell across the board, it's good to be aware of how far back your script will work.
I had a major issue when I was deploying a script to run against windows 7 workstations, where it couldn't cope with (command/variable).property and it was because they had version 1 or 2 running on them. Let's just say that wasn't my finest afternoon...
You must be logged in to reply to this topic.