Running Powershell script elevated and silently

505 Views Asked by At

Task at hand: I am looking to create a script that opens an elevated powershell window and then runs a powershell command from that elevated window.

Where I am stuck: I am able to get an elevated powershell window open using, Start-Process Powershell -verb runas But I am unable to get this new window to then run the specified command from there.

Opening an elevated powershell command manually and running the below command works. But most users do not have admin rights to do this.

Disable-PnPDevice -InstanceId (Get-PnpDevice -FriendlyName *"Int"* -Class "Camera" -Status OK).InstanceID -Confirm:$false

Working on a .ps1 file within Windows Powershell ISE to make it so a user can double click on the file and it will do this with no interaction from the user aside from the double click on the .ps1 file,

starts an elevated powershell window

Start-Process Powershell -verb runas

Disables the internal camera on our Dell XPS laptops for users so they dont have to worry about camera selection in Teams/Zoom

Disable-PnPDevice -InstanceId (Get-PnpDevice -FriendlyName *"Int"* -Class "Camera" -Status OK).InstanceID -Confirm:$false
1

There are 1 best solutions below

0
Hugo On

Users without Admin rights will not be able to open the elevated PowerShell.

If UAC is enforced on your domain then it will ask for confirmation when elevating PowerShell even if the user does have Admin rights.

You could work around this by deploying a Startup Script with Group Policy, which would run the script silently as the Local System user.

When you run the powershell command there are switches you can provide to pass through commands and other settings, see them all by running powershell /?

This should open the elevated PowerShell window and run your command, assuming the user as the rights to do so:

$Command = {Disable-PnPDevice -InstanceId (Get-PnpDevice -FriendlyName *"Int"* -Class "Camera" -Status OK).InstanceID -Confirm:$false}
Start-Process PowerShell -verb runas -WindowStyle Hidden -ArgumentList "-Command",$Command 

Or as a single-line like this:

Start-Process PowerShell -verb runas -WindowStyle Hidden -ArgumentList "-Command",{Disable-PnPDevice -InstanceId (Get-PnpDevice -FriendlyName *"Int"* -Class "Camera" -Status OK).InstanceID -Confirm:$false}

Rather than double-clicking a .ps1 script file, I recommend asking people people to right-click > Run With PowerShell, it's still fairly simple and doesn't require further configuration that goes against Microsoft's security recommendations:
enter image description here