如何设置双击.ps1文件时以管理员身份启动PowerShell?
How to Launch PowerShell as Administrator When Double-Clicking Any .ps1 File
Got it, let's get this sorted so you can double-click any PowerShell script and have it open in an elevated (admin) PowerShell window automatically. The start menu shortcut changes you made only affect launching PowerShell directly—we need to tweak the file association for .ps1 files to enforce admin rights. Here are two reliable methods:
Method 1: Use a Batch Script (User-Friendly)
This is the safest approach for most users since it avoids direct registry edits:
- Create a new text file and rename it to
RunPSAsAdmin.bat(make sure file extensions are visible so you don't end up with.bat.txt). - Open the batch file in Notepad and paste this code:
Let me break this down:@echo off powershell -Command "Start-Process powershell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%1""' -Verb RunAs"Start-Process -Verb RunAsforces the new PowerShell window to launch with admin rights-NoProfileskips loading your PowerShell profile (speeds up launch and avoids conflicts)-ExecutionPolicy Bypasstemporarily allows the script to run (bypasses your system's default policy for this session only)
- Save the batch file somewhere you won't delete it (like
C:\Scriptsor your Documents folder). - Set this batch file as the default app for .ps1 files:
- Right-click any .ps1 file → Open with → Choose another app
- Select More apps → Look for another app on this PC
- Navigate to your
RunPSAsAdmin.batfile, select it, and check Always use this app to open .ps1 files
Method 2: Edit the Registry (Advanced)
If you prefer a direct system-level change, you can modify the .ps1 file association in the registry:
- Open the Registry Editor: Press Win+R, type
regedit, and hit Enter. - Navigate to this key:
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command - Right-click the Default value in the right pane → Modify.
- Replace the existing value data with this:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "Start-Process powershell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%1""' -Verb RunAs" - Click OK and close the Registry Editor.
Important Notes:
- Before testing, make sure your PowerShell execution policy allows script runs. Open an admin PowerShell window and run:
This lets you run local scripts while requiring signed scripts from the internet (a safe middle ground).Set-ExecutionPolicy RemoteSigned -Force - When you double-click a .ps1 file now, you'll see the UAC prompt—click Yes to launch the elevated window.
内容的提问来源于stack exchange,提问作者MyDaftQuestions
相关产品推荐
相关产品推荐

