Powershell – Deploy a Powershell script and run on shutdown thru group policy

powershellshutdown

I have a Powershell script I need to deploy to my clients PC and then run it on shutdown.

I̶ ̶k̶n̶o̶w̶ ̶i̶t̶ ̶i̶s̶ ̶p̶o̶s̶s̶i̶b̶l̶e̶ ̶t̶o̶ ̶r̶u̶n̶ ̶P̶o̶w̶e̶r̶s̶h̶e̶l̶l̶ ̶s̶c̶r̶i̶p̶t̶s̶ ̶o̶n̶ ̶s̶h̶u̶t̶d̶o̶w̶n̶ (it seems I am having issues too with this), the problems is the script uses "local" path such as "$env:LOCALAPPDATA" and "C:\Windows\system32\someprogram.exe" so I think I need to copy it over first on the client's PC and then make it run on shutdown because of paths.

First off, what is the proper way to deploy a Powershell script to run on Shutdown thru group policy?

Is this the way it should be done?

Best Answer

Concerning local enviremental variables or paths in a powershell script, it is not important where the script file is located, but where it is executed.

Meaning, you just have to be shure that the paths and variables exist on the machine you want to execute the script on. Powershell will then use "his" local C:\Windows\System32\someprogram.exe, and not the one on the machine where the script file is located.

EDIT: Of course the client pc that wants to execute the script must reach the file somehow, so you must place it in a network share with proper security permissions or, if you use GPO for execution, in the sysvol share.

EDIT2:

Now the complete way for a shutdown powershell script delivered via GPO:

  • If you want to use a new GPO, create it.
  • Create the script you want to deliver.
  • Open Group Policy Editor on one of your DCs, and Edit the GPO you want to use for the shutdown script
  • Navigate to "Computer Configuration - Policies - Windows Settings - SCripts (Startup/Shutdown) - Shutdown"
  • Click "Add" - "Browse". Now you see the share path of the folder where Microsoft wants you to put the script. You can either use this path, or any other path in the Network with proper user rights.
  • Copy the script to the location you want it to be, best is to use the path predefined by Windows
    • if you want to use this predefined path, you have to know that the share path you see is write-protected. So you have to use the local sysvol path. Just replace \\yourdomain.local\SYSVOL\yourdomain.local by C:\Windows\SYSVOL\Domain
  • Now in the GPO-Window you can select the Script you want to execute - here you have to use the share path, not the local one!
  • while testing, also note that the Group Policy Object is saved after closing it. So if you change it and do not close the object, the changements won't take affect!