[英]How to provide C# RunSpace for PowerShell?
我正在嘗試打印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:檢索字符串時發生以下異常:“ Exception”,調用“ ToString”,參數為“ 0”:“此線程中沒有運行空間可用於運行腳本。 您可以在System.Management.Automation.Runspaces.Runspace類型的DefaultRunspace屬性中提供一個。 您嘗試調用的腳本塊是:$ this.ServiceName“”“ --->
PowerShell版本為3。VisualStudio版本為2010 Ultimate
調用腳本屬性時,我似乎遇到了類似的問題。 但是,要獲取所需的最快數據,請嘗試此操作。 修改命令(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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.