[Window PowerShell05]-C# 调用PowerShell脚本

本文介绍了一种使用C#和PowerShell结合的方法来实现高效且灵活的文件操作,通过C#代码处理流程,利用PowerShell的强大脚本功能完成复杂任务,如复制、删除文件、管理进程和服务、读取EventLog、操作注册表等,并展示了如何通过C#调用PowerShell脚本的简单例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       C# 和 PowerShell都是基于.net 平台面向对象的语言,由于PowerShell脚本功能强大,对于复制删除文件,管理进程和服务,读取EventLog,操作注册表等任务,PowerShell做起来很容易,我们可以将这些内容封装在PowerShell脚本中,C#代码仅做工作流的事情,这样发挥了脚本高效性的优势,脚本重用性强(可以使用Invoke运行在远程服务器上),而且修改简单。所以,使用C# 和脚本结合的方式是一种理想的组合。

       下面介绍一个简单的例子,说明C# 如何调用PowerShell脚本。

        private static string GetFileContent(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open);
            StreamReader reader = new StreamReader(fs);
            return reader.ReadToEnd();
        }

        private static string RunScript(string filePath)
        {
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();
            // open it
            runspace.Open();
            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();

            string scriptText = GetFileContent(filePath);

            pipeline.Commands.AddScript(scriptText);
            // add an extra command to transform the script output objects into nicely formatted strings
            // remove this line to get the actual objects that the script returns. For example, the script
            // "Get-Process" returns a collection of System.Diagnostics.Process instances.
            //pipeline.Commands.Add("Out-String");
            // execute the script
            System.Collections.ObjectModel.Collection<PSObject> results = pipeline.Invoke();
            // close the runspace
            runspace.Close();
            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            return stringBuilder.ToString();
        }

        static void Main(string[] args)
        {
            string filePath = "1.ps1";
            RunScript(filePath);
            Console.ReadKey();
        }

         不仅如此,可以通过C# 给脚本传参数,下一篇会介绍。

要在PowerShell中获取Windows当前活动窗口的名称,可以借助于Windows API函数以及.NET Framework。然而,直接通过PowerShell本身并没有内置命令可以直接取得这个信息。 一种常见的做法是利用`Add-Type` cmdlet添加C#代码,并结合使用用户32位DLL (`User32.dll`) 中的一些API如 `GetForegroundWindow` 和 `GetWindowText` 来完成此操作: ```powershell $signature = @" using System; using System.Runtime.InteropServices; public class WindowInfo { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); public static string GetCurrentWindowTitle() { const int nChars = 256; IntPtr handle = GetForegroundWindow(); if (handle == IntPtr.Zero) return "No window"; StringBuilder stringBuilder = new StringBuilder(nChars); if (GetWindowText(handle, stringBuilder, nChars) > 0) return stringBuilder.ToString(); else return "Unknown"; } } "@ Add-Type $signature [currentwindowinfo]::GetCurrentWindowTitle() ``` 上述脚本首先定义了一段包含两个PInvoke声明的 C# 代码片段——用于访问 Windows 的非托管功能;然后将其编译并加载到正在运行的 PowerShell 进程中。最后调用了静态方法 `GetCurrentWindowTitle()` ,它会返回前台窗口标题作为字符串。 请注意,在某些情况下(例如当屏幕锁定或远程桌面连接断开时),可能无法准确获得预期的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值