I type this in PowerShell running as administrator to remove 3D Builder:

C:\Windows\System32>get-appxpackage *3dbuilder* | remove-appxpackage

It works fine, but how can I write the line in a Batch file to do the same thing?


The reason that this will not work is that a PowerShell script is very different from a batch file both in terms of its contents AND the way windows (by default) will handle it.

For Example - if you save Write-Host $ENV:COMPUTERNAME into a PowerShell (.ps1) file and double click it - it wil most likely open in Notepad!

If you really want to have this single line PowerShell command into a batch file - you want something like powershell.exe -command "get-appxpackage *3dbuilder* | remove-appxpackage" saved inside your batch file. You should then be able to right click and "run as Administrator" on the batch file to get your desired effects.

Failing that - if you have a .ps1 PowerShell script - you can call it from a batch file using PowerShell.exe -File C:\Folder\script.ps1 and run it from an administrative command line.

Alternatively, you will need to open PowerShell (or ISE) as an administrator and execute the script (& C:\Folder\file.ps1)

Lastly - you can use the -verb RunAs switch to try and force elevation if needed when calling PowerShell.exe or you can use the following block of script inside your script to cause a session to elevate (with a UAC prompt if needed):

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {  

  $arguments = "& '" + $myinvocation.mycommand.definition + "'"
   Start-Process powershell -Verb runAs -ArgumentList $arguments

###My Script Code Goes Here and will be executed if I am an administrator!

Side note - you could go down the horrible route of reconfiguring windows to open PowerShell scripts into PowerShell and/or add a windows context menu to run in powershell as an admin - but this is messy and dangerous to say the least.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.