我有一个我编写的自定义 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/