I'm currently responsible for upgrading all PCs to Windows 11 at my job. Part of this process involves removing an outdated version of Outlook via a PowerShell script. I've renamed my removal script to a .ps1 file, but it doesn't run as expected unless I manually launch PowerShell with administrator rights. Since right-clicking to run as admin isn't working for me, is there any way to automate this? Is it possible to have the PowerShell script invoke a command line that does run as an admin? Here's my current removal script for reference: Remove-AppxProvisionedPackage -AllUsers -Online -PackageName (Get-AppxPackage Microsoft.OutlookForWindows).PackageFullName
5 Answers
Do you have access to management tools like SCCM or Intune? They can run your PowerShell scripts across the network without needing to manually touch each device. It could save you a ton of time and headaches!
To ensure your script runs with elevated rights, you can include this check at the start:
```powershell
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit
}
```
Just add that to the top of your script and you’ll get a UAC prompt when you run it!
Just a heads-up: this will start PowerShell 5.1, not any newer versions like 7.
You could also use the `Start-Process` command with the `-Verb RunAs` option in your script to achieve the same result when starting an elevated session.
If you're looking to relaunch your script with admin privileges, there's definitely a way. I typically prefer using a batch file to handle the startup as they can be double-clicked and often bypass any execution policy issues. Here’s a snippet you could use:
```powershell
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "Relaunching as admin..." -ForegroundColor Yellow
Start-Process wt "powershell -File `"$PSCommandPath`"" -Verb RunAs; exit
}
Write-Host "Running with admin privileges" -ForegroundColor Green
// Your removal script here
```
Using this should help you get going!
Haha, that sounds about right!
A workaround I’ve used before involved creating a batch script that runs as admin, which then calls your PowerShell script. This method simplifies the process significantly. Just make sure your PowerShell command blocks are included properly in the batch script.
I do have those tools! Definitely something I need to explore more.