我正在尝试打印Powershell脚本的响应,该脚本向我显示在远程主机上运行的服务。
Get-Service -ComputerName "ComputerName"
当我在Powershell上运行时,我得到了所需的输出。但是当我使用C#尝试相同的操作时,我得到以下异常。
此线程中没有可用于运行脚本的Runspace。您可以 在。的DefaultRunspace属性中提供一个 System.Management.Automation.Runspaces.Runspace类型。
我正在使用的代码是:
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;
}
}
编辑: 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
使用C#输出
System.Management.Automation.ExtendedTypeSystemException:The 检索字符串时发生以下异常:“异常 使用“0”参数调用“ToString”:“没有运行空间 可用于在此线程中运行脚本。你可以提供一个 的DefaultRunspace属性 System.Management.Automation.Runspaces.Runspace类型。脚本块 你试图调用的是:$ this.ServiceName“”--->
PowerShell版本是3。 Visual Studio版本是2010 Ultimate
答案 0 :(得分:1)
在调用脚本属性时,我看起来有类似的问题。但要获得最快的数据,请尝试使用此功能。修改命令(var脚本),然后在(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();
}
}