我想将一个C#对象传递给Power
Shell,这样我就可以为主UI提供状态更新.我在SO上看过几篇关于此的帖子,但它们似乎都没有帮助解决我的问题.
Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; runspace.open(); runspace.SessionStateProxy.Setvariable("LogReporter",this.LogReporter); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(script); StringBuilder builder = new StringBuilder(); Collection<PSObject> objects = pipeline.Invoke();
在PowerShell脚本中,我想访问LogReporter(基本类型:System.Windows.Window),如下面的代码片段所示
$RunningInstances= @(Get-ChildItem | Where-Object { $_.InstanceStatus.ToString() -eq "Running" }) $LogReporter.ReportProgress($RunningInstances.Count.ToString() + " instances running currently...")
但是,我得到的只是
You cannot call a method on a null-valued expression. at CallSite.Target(Closure,CallSite,Object,Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site,T0 arg0,T1 arg1) at System.Management.Automation.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
我试图列出$LogReporter变量的所有成员,但结果是
No object has been specified to the get-member cmdlet.
这意味着$LogReporter变量为null.现在的问题是:为什么以及如何解决这个问题?
请注意,为了更好的可读性,代码略有简化,但显示了必要和失败的部分.
什么出问题的任何想法?我必须以某种方式注册我的LogReporter类型吗?
我感谢任何帮助!
解
解决方法
这是完整的工作样本,向您展示问题.问题不在于LogReporter变量,而在于“$_.InstanceStatus.ToString()”部分.在您的情况下,InstanceStatus为null,ToString()抛出上面的异常.在下面的代码中,我刚刚删除了ToString()调用,并且您看到来自LogReporter的“0实例正在运行”消息.
class Program { private static void Main(string[] args) { new ScriptRunner().Run(); Console.ReadKey(); } } class ScriptRunner { public ScriptRunner() { this.LogReporter = new LogReporter(); } public void Run() { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; runspace.open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript("$RunningInstances=@(Get-ChildItem | Where-Object {$_.InstanceStatus -eq \"Running\"})"); runspace.SessionStateProxy.Setvariable("LogReporter",this.LogReporter); pipeline.Commands.AddScript("$LogReporter.ReportProgress($RunningInstances.Count.ToString()+\" instances running currently...\")"); StringBuilder builder = new StringBuilder(); Collection<PSObject> objects = pipeline.Invoke(); } public LogReporter LogReporter { get; private set; } } class LogReporter { public void ReportProgress(string msg) { Console.WriteLine(msg); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。