首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从c#powershell脚本执行中提取$ lastexitcode

从C# PowerShell脚本执行中提取$lastexitcode是指在C#中执行PowerShell脚本,并在脚本执行完成后获取$lastexitcode变量的值。$lastexitcode是PowerShell中的一个特殊变量,用于存储上一个执行的命令的退出代码。在C#中,可以使用PowerShell类库来执行PowerShell脚本,并获取$lastexitcode的值。

以下是一个示例代码,展示如何在C#中执行PowerShell脚本并获取$lastexitcode的值:

代码语言:csharp
复制
using System;
using System.Management.Automation;

namespace PowerShellExample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PowerShell powerShell = PowerShell.Create())
            {
                // 添加PowerShell脚本
                powerShell.AddScript("Get-Process | Where-Object { $_.Name -eq 'notepad' } | Stop-Process");
                
                // 执行脚本
                powerShell.Invoke();

                // 获取$lastexitcode的值
                var exitCode = powerShell.Runspace.SessionStateProxy.GetVariable("lastexitcode");

                Console.WriteLine($"The last exit code was: {exitCode}");
            }
        }
    }
}

在这个示例中,我们使用PowerShell类库创建了一个PowerShell实例,并添加了一个PowerShell脚本,该脚本将停止所有名称为“notepad”的进程。然后,我们调用PowerShell实例的Invoke方法来执行脚本。最后,我们使用PowerShell实例的Runspace.SessionStateProxy.GetVariable方法获取$lastexitcode的值,并将其输出到控制台。

需要注意的是,在C#中执行PowerShell脚本需要引用System.Management.Automation命名空间,因此需要在C#项目中添加对该命名空间的引用。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券