c# - PowerShell - 从对象方法中写入进度

标签 c# powershell

我有一个我编写的自定义 C# PowerShell Cmdlet,它输出一个对象。

[Cmdlet(VerbsCommon.Get, "CustomObj")]
public class CustomObjGet : Cmdlet
{
    protected override void ProcessRecord()
    {
        var instance = CustomObj.Get();
        WriteObject(instance);
    }
}

用法:

$output = Get-CustomObj

返回的对象有一个方法:

public class CustomObj
{
    public string Name { get; set; }

    public static CustomObj Get()
    {
        var instance = new CustomObj() { Name = "Testing" };
        return instance;
    }

    public void RestartServices () 
    {
        // Want to WriteProgress here...
    }
}

用法:

$output.RestartServices()

就目前而言,该方法无法像在 Cmdlet 本身的 ProcessRecord() 方法中那样访问 Cmdlet WriteProgress 函数。

我想从该方法中执行 PowerShell WriteProgress。关于如何做到这一点有什么想法吗?

最佳答案

抱歉,误读了问题。这似乎在我的有限测试中有效:

    public void RestartServices()
    {
        //Write
        // Want to WriteProgress here...
        for (int i = 0; i <= 100; i += 10)
        {
            Console.WriteLine("i is " + i);
            UpdateProgress(i);
            Thread.Sleep(500);
        }
    }

    private void UpdateProgress(int percentComplete)
    {
        var runspace = Runspace.DefaultRunspace;
        var pipeline = runspace.CreateNestedPipeline("Write-Progress -Act foo -status bar -percentComplete " + percentComplete, false);
        pipeline.Invoke();
    }

仅供引用,在 PowerShell V3 中,您也可以这样做:

    private void UpdateProgressV3(int percentComplete)
    {
        Collection<PSHost> host = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Get-Variable").AddParameter("-ValueOnly").AddArgument("Host").Invoke<PSHost>();
        PSHostUserInterface ui = host[0].UI;
        var progressRecord = new ProgressRecord(1, "REstarting services", String.Format("{0}% Complete", percentComplete));
        progressRecord.PercentComplete = percentComplete;
        ui.WriteProgress(1, progressRecord);
    }

关于c# - PowerShell - 从对象方法中写入进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12045749/

相关文章:

c# - 强制 Visual Studio 调试工具显示有用的信息

xml - PowerShell:通过名称为 "ADDRESS"的 XML 进行解析

powershell - 如何在powershell中使用findstr在整个驱动器中搜索字符串?

powershell - 使用Powershell删除重复的文件

c# - 如何开始开发 Internet Explorer 扩展?

c# - 多个.cs文件访问一个Windows窗体

c# - 如何使用 MS-IoT Lightning 设置/获取 Raspberry Pi2 的 PWM?

c# - 在特定时间运行 Windows 服务

java - “UTF-8” 编码在 java 构建中不起作用

powershell - 高级安装程序 powershell 脚本集属性