I had created an article earlier for running powershell script from Uipath. However, some scripts need to be run as Administrator and so it gets difficult to run the script via Uipath.
The solution below uses a batch file to run powershell with administrator privileges.
Let’s consider an example where user needs to work on two different windows services.
- Start a windows service (Requires to be run as Administrator)
- Get the info about a windows service and save it to text file (This does not require to run as administrator, but added for parameters example)
The user will then create a powershell script and pass the two service names as parameters.
Create Powershell Script as below
StopService and GetServiceStatus are the input parameters to this script. Both are names of the services.
The first one will be stopped and second one’s status will be saved to text file.
Save the powershell script as PSScript.ps1
Create Batch File as below:
%1 and %2 are input arguments to batch file and this will be passed as parameters to Powershell script. The arguments names ‘StopService’ and ‘GetServiceStatus’ should match to the ones used in Powershell script.
(The batch file supports up to 9 parameters. You can add or remove the parameters as per need.)
Save the batch file as PSScript.bat
Note: Use same name for batch file and powershell file as per bat file logic. Alternativley, you can try to pass the Powershell script file name as a parameter to batch file.
Run the Batch file from Uipath by using Start process activity.
- Create two variables for passing the arguments and assign the values to them (PS_StopService and PS_GetServiceStatus).
- Combine these variables into single space seperated string and save (Bat_Arguments).
- Use start process activity and provide the file path of batch file created earlier.
- Pass the arument ‘Bat_Arguments’.
- Run the XAML file.
- Check if the service name passed to ‘PS_StopService’ is stopped.
- Check if the information is logged for service name passed to ‘PS_GetServiceStatus’.
Example is attached.
PSAdmin.zip (23.2 KB)
Some Important Points:
“powershell –ExecutionPolicy Bypass” will start a PowerShell session that allows for running scripts and keeps the lowered permissions isolated to just the current running process as explained here
-Verb RunAs - Starts PowerShell by using the Run as administrator option. Details here