Reputation: 6863
I have been experimenting with two different approaches to finalizing a script. I need to offer different ways to complete the script, depending on user needs, like Logoff, Restart and Shutdown. I have tried two approaches, a Shutdown.exe based approach, and a Get-WmiObject approach. Like this...
Shutdown.exe -r -t 0
or
(Get-WmiObject win32_operatingsystem -nameSpace:'root\CIMV2' -computerName:'.').Win32Shutdown(2) > $null
The problem is that in different situations each works or doesn't. The former approach works on my Windows Home machine while the latter fails with a "Privilege not held" error. On the other hand, on a series of Windows 7 machines last week the former did nothing and the latter worked fine. I am hoping someone can verify if this is indeed a Home vs Pro thing, or if there might be something else at play? To add complexity to the issue, I also need to be able to run the script as a remote job, and ideally would rather not need an alternative approach. Is there some global solution here? Or do I need to perhaps go the ugly kludge route of using both, trusting one of the two will work in any condition?
EDIT: Per Tony's comment I am now using variations on this in a switch.
try {
(Get-WmiObject win32_operatingsystem -nameSpace:'root\CIMV2' -computerName:'.').Win32Shutdown(1) > $null
} catch {
Shutdown.exe /s /t 0
}
Upvotes: 1
Views: 808
Reputation: 4742
In the case of script commands to shut down or reboot computers, I would highly recommend that you use more than one method unless you have a tightly controlled, heterogeneous environment where you can thoroughly test one method to the point where you are assured it will be reliable.
Although issuing two or three different shutdown commands might be considered "messy," IT is sometimes messy, is it not? I know doing something like this can make you feel rather dirty, but rest assured that you'll forget about it in a couple of weeks and it will no longer show up in your nightmares as a giant ogre that is needless running commands on your computers. :)
This is just from my experience, so there's no documentation to cite. If there are some comments with compelling arguments to the contrary, or a better answer, I'll be glad to delete this answer.
Upvotes: 1