學powershell有一個星期了吧,一直為這種批處理的運行模式煩惱。按照以下步驟操作後的效果是:
直接.ps1檔案可以以管理員身份使用powershell.exe運行代碼。
在.ps1檔案上右鍵點edit,可以用PowerGUI進行開發。
1.安裝PowerGUI。
2.在安裝目錄下,打到exe,右鍵屬性,設定為以管理員啟動。
3.(此步驟為開啟UAC的系統使用)編譯:PowerShellAgent.exe。(如果已經有了,不用再次編譯。)
由於預設的ps1檔案的右鍵命令Run with powershell不是以管理員身份運行,所以很多命令都會執行失敗。而powershell.exe和cmd.exe等進程是OS內建的,不能設定預設以管理員運行。所以這裡建立一個新的exe,代理到powershell.exe。然後再設定此程式預設以管理員運行即可。(同樣的方法可以使用在CMD上。)代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace PowerShellAgent
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe");
if (args.Length > 0)
{
StringBuilder fileName = new StringBuilder();
for (int i = 0; i < args.Length; i++)
{
fileName.Append(args[i]);
if (i < args.Length)
{
fileName.Append(' ');
}
}
p.StartInfo.Arguments = string.Format("-NoExit -File \"{0}\"", fileName);//如果需要在執行完畢後關閉powershell,則可以把-NoExit去掉。
}
p.Start();
}
}
}
4.(此步驟為開啟UAC的系統使用)找到PowerShellAgent.exe,右鍵屬性,設定為以管理員啟動。
5.(此步驟為開啟UAC的系統使用)以管理員身份運行cmd命令關聯預設的.ps1檔案程式為PowerShellAgent.exe。命令如下:
ftype Microsoft.PowerShellScript.1=E:\Backup\PowerShellAgent.exe %1 %*
上面的E:\Backup\是PowerShellAgent.exe檔案夾路徑,自行更改。
使用這步是因為PowerGUI在安裝完成後,不能再使用視窗設定.ps1檔案的預設開啟程式。(這軟體真是可惡!)
6.(此步驟為未開啟UAC的系統使用)運行cmd命令關聯預設的.ps1檔案程式為PowerShell.exe。命令如下:
ftype Microsoft.PowerShellScript.1=C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe %1 %*
如果還要修改易用性,可到註冊表中找到以下路徑進行修改:HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\