2017-05-09 23 views
0

我试图打印显示我在远程主机上运行的服务的Powershell脚本的响应。如何为PowerShell提供C#RunSpace?

Get-Service -ComputerName "ComputerName" 

当我在Powershell上运行这个,我得到所需的输出。但是当我使用C#尝试相同时,我得到以下异常。

没有Runspace可用于在此线程中运行脚本。您可以在 System.Management.Automation.Runspaces.Runspace类型的DefaultRunspace属性中提供一个 。

,我正在使用的代码是:用C# 输出在PowerShell中

Status Name    DisplayName 
------ ----    ----------- 
Stopped AdtAgent   Microsoft Monitoring Agent Audit Fo... 
Stopped AeLookupSvc  Application Experience 
Stopped ALG    Application Layer Gateway Service 
Stopped AppIDSvc   Application Identity 
Running Appinfo   Application Information 
Stopped AppMgmt   Application Management 
Stopped AppReadiness  App Readiness 
Stopped AppXSvc   AppX Deployment Service (AppXSVC) 
Stopped AudioEndpointBu... Windows Audio Endpoint Builder 
Stopped Audiosrv   Windows Audio 
Running BFE    Base Filtering Engine 
Running BITS    Background Intelligent Transfer Ser... 
Running BrokerInfrastru... Background Tasks Infrastructure Ser... 
Stopped Browser   Computer Browser 
Running CcmExec   SMS Agent Host 
Running CertPropSvc  Certificate Propagation 
Stopped CmRcService  Configuration Manager Remote Control 
Running COMSysApp   COM+ System Application 
Running CryptSvc   Cryptographic Services 
Running DcomLaunch   DCOM Server Process Launcher 
Stopped defragsvc   Optimize drives 

输出

System.Management.Automation:

 var powerShell = PowerShell.Create().AddScript(script); 

     var results = powerShell.Invoke(); 

     foreach (var item in results) 
     { 
      try 
      { 
       Console.WriteLine(item); 
      } 
      catch (ExtendedTypeSystemException e) 
      { 
       Console.WriteLine(e); 
       break; 
      } 
     } 

编辑。 ExtendedTypeSystemException:在e之后的 xception在检索字符串时发生:“例外 使用”0“参数调用”ToString“:”没有运行脚本的运行空间 可用于此线程。您可以在 System.Management.Automation.Runspaces.Runspace类型的 DefaultRunspace属性中提供一个。 您曾尝试调用的脚本块是:$ this.ServiceName“” --->

PowerShell的版本是3 的Visual Studio版本是2010旗舰版

回答

0

貌似我已经当了类似的问题调用脚本属性。但要获得最快速的数据,请尝试一下。修改命令(var script),然后在(thing.Members [%%%%%]。Value)的位置需要放置要拉取或查看的PowerShell属性。 (注意以下)

class Program 
{ 
    static void Main(string[] args) 
    { 
     var script = "Get-NetIPAddress "; 

     var powerShell = PowerShell.Create().AddScript(script).Invoke(); 

     foreach (var thing in powerShell) 
     { 
      try 
      { 
       //the Members must be PROPERTIES of the PowerShell object 
       var name = (thing.Members["InterfaceAlias"].Value); 
       var ip= (thing.Members["IPv4Address"].Value); 

       Console.WriteLine("Connection: " + name + " .......... IP: " + ip); 
      } 
      catch 
      { 

      } 

     } 

     Console.Read(); 
    } 
}