091031 T PowerShell Solution

简介:

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

目录
相关文章
|
Shell 数据安全/隐私保护