当前位置: 首页 > 编程语言 > C#

从C#调用远程Powershell命令Share

时间:2023-04-11 00:20:03 C#

从C#调用远程Powershell命令我只想运行这个简单的命令:invoke-command-ComputerNamemycomp.mylab.com-ScriptBlock{"get-childitemC:windows"}在C#代码中,我执行以下操作:InitialSessionStateinitial=InitialSessionState.CreateDefault();运行空间runspace=RunspaceFactory.CreateRunspace(initial);运行空间.Open();PowerShellps=PowerShell.Create();ps.Runspace=运行空间;ps.AddCommand("调用命令");ps.AddParameter("ComputerName","mycomp.mylab.com");ps.AddParameter("ScriptBlock","get-childitemC:\windows");foreach(PSObjectobjinps.Invoke()){//DoSomething}当我运行时,我得到一个异常:无法绑定参数'ScriptBlock'。无法将“System.String”类型的“get-childitemC:windows”值转换为“System.Management.Automation.ScriptBlock”类型。我想我需要在某处使用ScriptBlock类型,但不知道该怎么做。这只是一个简单的示例,真正的用例将涉及使用多个命令运行更大的脚本块,因此非常感谢任何有关如何执行此操作的帮助。谢谢啊,ScriptBlock本身的参数需要是ScriptBlock类型。完整代码:InitialSessionStateinitial=InitialSessionState.CreateDefault();运行空间runspace=RunspaceFactory.CreateRunspace(initial);运行空间.Open();PowerShellps=PowerShell.Create();ps.Runspace=运行空间;ps.AddCommand("调用命令");ps.AddParameter("ComputerName","mycomp.mylab.com");ScriptBlockfilter=ScriptBlock.Create("Get-childitemC:\windows");ps.AddParameter("脚本块",过滤器);foreach(PSObjectobjinps.Invoke()){//DoSomething}如果有人认为它在未来有用,请在这里回答scriptblock字符串应匹配“{...}”格式。使用以下代码:ps.AddParameter("ScriptBlock","{get-childitemC:\windows}");您可以使用缩写形式:ps.AddParameter("ScriptBlock",ScriptBlock.Create("Get-childitemC:\windows}");\Windows"));如果在某些情况下它可能更合适,则作为替代方案。varremoteComputer=newUri(String.Format("{0}://{1}:5985/wsman","HTTP","ComputerName"));varconnection=newWSManConnectionInfo(remoteComputer,null,TopTest.GetCredential());varrunspace=RunspaceFactory.CreateRunspace(连接);运行空间.Open();varpowershell=PowerShell.Create();powershell.Runspace=运行空间;powershell.AddScript("$env:ComputerName");varresult=powershell.Invoke();https://blogs.msdn.microsoft.com/schlepticons/2012/03/23/powershell-automation-and-remoting-ac-love-story/以上就是C#学习教程:从C#调用远程的所有内容分享通过powershell命令,如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: