091031 T PowerShell Solution

來源:互聯網
上載者:User

學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\

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.