Shell – Creating a Powershell script to open as Administrator and run command

powershell

I'm new to Powershell scripting but have a need to create a script to run on everyone's computer in my office. The script I need to run requires Powershell to run as Administrator. When I use the "runas" command, another Powershell window opens but my commands run in the original Powershell window, which doesn't have sufficient privileges. The commands I need to run in the Administrator window (privileges) are:

Get-AppxPackage -AllUsers -Name Microsoft.3DBuilder | Remove-AppxPackage
Get-AppxPackage -AllUsers -Name Microsoft.GetStarted | Remove-AppxPackage
Get-AppxPackage -AllUsers -Name Microsoft.Skypass | Remove-AppxPackage 
Get-AppxPackage -AllUsers -Name Microsoft.MicrosoftSolitaireCollection | Remove-AppxPackage

Best Answer

What version of powershell are you running?

If you are using 4.0 or above you can use the #Requires statement

In your case:

#Requires -RunAsAdministrator

When the script runs on the local machine it will ensure that the script is in elevated administrator mode.

Related Question