C# Invoke Powershell with pre-created object

前端 未结 1 1198
天命终不由人
天命终不由人 2021-01-21 13:16

I\'ve just started out with PS and are writing some C# classes which I need to test from within PS.

Please note that these classes are NOT CmdLets.

1条回答
  •  礼貌的吻别
    2021-01-21 13:54

    I found a solution:

            var objs= new PSDataCollection {obj};
    
            using (var ps = PowerShell.Create())
            {
                ps.Runspace.SessionStateProxy.SetVariable("objList", objs);
                ps.AddScript(@"$objList| ForEach { $_.Run()}");
                ps.AddCommand("Out-String");
                var output = ps.Invoke();
    
                var stringBuilder = new StringBuilder();
                foreach (var obj in output)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }
    
                var result = stringBuilder.ToString().Trim();
    
                //Evaluate result.
            }
    

    0 讨论(0)
提交回复
热议问题