我正在尝试打印Powershell脚本的响应,该脚本显示在远程主机上运行的服务。
Get-Service -ComputerName "ComputerName"当我在Powershell上运行这个程序时,我得到了所需的输出。但是,当我使用C#进行相同的尝试时,我会得到以下异常。
在这个线程中没有运行脚本的运行空间。您可以在System.Management.Automation.Runspaces.Runspace类型的DefaultRunspace属性中提供一个。
我使用的代码是:
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:以下异常是在检索字符串时发生的:“异常调用带有"0”参数的"ToString“:”此线程中没有运行脚本可用的运行空间。您可以在System.Management.Automation.Runspaces.Runspace类型的DefaultRunspace属性中提供一个。您试图调用的脚本块是:$this.ServiceName"“->
PowerShell版本为3,Visual版本为2010终极版
发布于 2017-08-31 17:34:57
看来我在调用脚本属性时遇到了类似的问题。但是要想得到你要找的最快的数据,试试这个。修改命令(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();
}
}https://stackoverflow.com/questions/43869347
复制相似问题