本文整理汇总了C#中System.Management.Automation.Runspaces.Runspace类的典型用法代码示例。如果您正苦于以下问题:C# Runspace类的具体用法?C# Runspace怎么用?C# Runspace使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Runspace类属于System.Management.Automation.Runspaces命名空间,在下文中一共展示了Runspace类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PSTestScope
public PSTestScope(bool connect = true)
{
SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];
var iss = InitialSessionState.CreateDefault();
if (connect)
{
SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);
iss.Commands.Add(ssce);
}
_runSpace = RunspaceFactory.CreateRunspace(iss);
_runSpace.Open();
if (connect)
{
var pipeLine = _runSpace.CreatePipeline();
Command cmd = new Command("connect-sponline");
cmd.Parameters.Add("Url", SiteUrl);
if (!string.IsNullOrEmpty(CredentialManagerEntry))
{
cmd.Parameters.Add("Credentials", CredentialManagerEntry);
}
pipeLine.Commands.Add(cmd);
pipeLine.Invoke();
}
}
示例2: ScriptDebugger
public ScriptDebugger(bool overrideExecutionPolicy, DTE2 dte2)
{
HostUi = new HostUi(this);
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ApartmentState = ApartmentState.STA;
iss.ThreadOptions = PSThreadOptions.ReuseThread;
_runspace = RunspaceFactory.CreateRunspace(this, iss);
_runspace.Open();
_runspaceRef = new RunspaceRef(_runspace);
//TODO: I think this is a v4 thing. Probably need to look into it.
//_runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
//Provide access to the DTE via PowerShell.
//This also allows PoshTools to support StudioShell.
_runspace.SessionStateProxy.PSVariable.Set("dte", dte2);
ImportPoshToolsModule();
LoadProfile();
if (overrideExecutionPolicy)
{
SetupExecutionPolicy();
}
SetRunspace(Runspace);
}
示例3: InitializeTests
public void InitializeTests()
{
RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException warning;
config.AddPSSnapIn("ShareFile", out warning);
runspace = RunspaceFactory.CreateRunspace(config);
runspace.Open();
// do login first to start tests
using (Pipeline pipeline = runspace.CreatePipeline())
{
Command command = new Command("Get-SfClient");
command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));
pipeline.Commands.Add(command);
Collection<PSObject> objs = pipeline.Invoke();
Assert.AreEqual<int>(1, objs.Count);
sfLogin = objs[0];
}
}
示例4: RawExecute
public static Collection<PSObject> RawExecute(string[] commands)
{
LastRawResults = null;
LastUsedRunspace = InitialSessionState == null ?
RunspaceFactory.CreateRunspace() : RunspaceFactory.CreateRunspace(InitialSessionState);
LastUsedRunspace.Open();
foreach (var command in commands)
{
using (var pipeline = LastUsedRunspace.CreatePipeline())
{
pipeline.Commands.AddScript(command, true);
try
{
LastRawResults = pipeline.Invoke();
}
catch (Exception)
{
LastRawResults = pipeline.Output.ReadToEnd();
throw;
}
if (pipeline.Error.Count > 0)
{
throw new MethodInvocationException(String.Join(Environment.NewLine, pipeline.Error.ReadToEnd()));
}
}
}
return LastRawResults;
}
示例5: ExchPowershell
/// <summary>
/// Creates a new class and stores the passed values containing connection information
/// </summary>
/// <param name="uri">The URI to the Exchange powershell virtual directory</param>
/// <param name="username">DOMAIN\Username to authenticate with</param>
/// <param name="password">Password for the domain user</param>
/// <param name="isKerberos">True if using kerberos authentication, False if using basic authentication</param>
/// <param name="domainController">The domain controller to communicate with</param>
public ExchPowershell()
{
try
{
// Retrieve the settings from the database
SchedulerRetrieve.GetSettings();
// Set our domain controller to communicate with
this.domainController = Config.PrimaryDC;
// Get the type of Exchange connection
bool isKerberos = false;
if (Config.ExchangeConnectionType == Enumerations.ConnectionType.Kerberos)
isKerberos = true;
// Create our connection
this.wsConn = GetConnection(Config.ExchangeURI, Config.Username, Config.Password, isKerberos);
// Create our runspace
runspace = RunspaceFactory.CreateRunspace(wsConn);
// Open our connection
runspace.Open();
}
catch (Exception ex)
{
// ERROR
logger.Fatal("Unable to establish connection to Exchange.", ex);
}
}
示例6: P0wnedListenerConsole
public P0wnedListenerConsole()
{
InitialSessionState state = InitialSessionState.CreateDefault();
state.AuthorizationManager = new System.Management.Automation.AuthorizationManager("Dummy");
this.myHost = new MyHost(this);
this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost, state);
this.myRunSpace.Open();
lock (this.instanceLock)
{
this.currentPowerShell = PowerShell.Create();
}
try
{
this.currentPowerShell.Runspace = this.myRunSpace;
PSCommand[] profileCommands = p0wnedShell.HostUtilities.GetProfileCommands("p0wnedShell");
foreach (PSCommand command in profileCommands)
{
this.currentPowerShell.Commands = command;
this.currentPowerShell.Invoke();
}
}
finally
{
lock (this.instanceLock)
{
this.currentPowerShell.Dispose();
this.currentPowerShell = null;
}
}
}
示例7: PipelineBase
/// <summary>
/// Create a Pipeline with an existing command string.
/// Caller should validate all the parameters.
/// </summary>
/// <param name="runspace">
/// The LocalRunspace to associate with this pipeline.
/// </param>
/// <param name="command">
/// The command to invoke.
/// </param>
/// <param name="addToHistory">
/// If true, add the command to history.
/// </param>
/// <param name="isNested">
/// If true, mark this pipeline as a nested pipeline.
/// </param>
/// <param name="inputStream">
/// Stream to use for reading input objects.
/// </param>
/// <param name="errorStream">
/// Stream to use for writing error objects.
/// </param>
/// <param name="outputStream">
/// Stream to use for writing output objects.
/// </param>
/// <param name="infoBuffers">
/// Buffers used to write progress, verbose, debug, warning, information
/// information of an invocation.
/// </param>
/// <exception cref="ArgumentNullException">
/// Command is null and add to history is true
/// </exception>
/// <exception cref="ArgumentNullException">
/// 1. InformationalBuffers is null
/// </exception>
protected PipelineBase(Runspace runspace,
CommandCollection command,
bool addToHistory,
bool isNested,
ObjectStreamBase inputStream,
ObjectStreamBase outputStream,
ObjectStreamBase errorStream,
PSInformationalBuffers infoBuffers)
: base(runspace, command)
{
Dbg.Assert(null != inputStream, "Caller Should validate inputstream parameter");
Dbg.Assert(null != outputStream, "Caller Should validate outputStream parameter");
Dbg.Assert(null != errorStream, "Caller Should validate errorStream parameter");
Dbg.Assert(null != infoBuffers, "Caller Should validate informationalBuffers parameter");
Dbg.Assert(null != command, "Command cannot be null");
// Since we are constructing this pipeline using a commandcollection we dont need
// to add cmd to CommandCollection again (Initialize does this).. because of this
// I am handling history here..
Initialize(runspace, null, false, isNested);
if (true == addToHistory)
{
// get command text for history..
string cmdText = command.GetCommandStringForHistory();
HistoryString = cmdText;
AddToHistory = addToHistory;
}
//Initialize streams
InputStream = inputStream;
OutputStream = outputStream;
ErrorStream = errorStream;
InformationalBuffers = infoBuffers;
}
示例8: GetCommandSynopsis
/// <summary>
/// Gets the command's "Synopsis" documentation section.
/// </summary>
/// <param name="commandInfo">The CommandInfo instance for the command.</param>
/// <param name="runspace">The Runspace to use for getting command documentation.</param>
/// <returns></returns>
public static string GetCommandSynopsis(
CommandInfo commandInfo,
Runspace runspace)
{
string synopsisString = string.Empty;
PSObject helpObject = null;
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.Runspace = runspace;
powerShell.AddCommand("Get-Help");
powerShell.AddArgument(commandInfo);
helpObject = powerShell.Invoke<PSObject>().FirstOrDefault();
}
if (helpObject != null)
{
// Extract the synopsis string from the object
synopsisString =
(string)helpObject.Properties["synopsis"].Value ??
string.Empty;
// Ignore the placeholder value for this field
if (string.Equals(synopsisString, "SHORT DESCRIPTION", System.StringComparison.InvariantCultureIgnoreCase))
{
synopsisString = string.Empty;
}
}
return synopsisString;
}
示例9: SymbolDetails
internal SymbolDetails(
SymbolReference symbolReference,
Runspace runspace)
{
this.SymbolReference = symbolReference;
// If the symbol is a command, get its documentation
if (symbolReference.SymbolType == SymbolType.Function)
{
CommandInfo commandInfo =
CommandHelpers.GetCommandInfo(
symbolReference.SymbolName,
runspace);
this.Documentation =
CommandHelpers.GetCommandSynopsis(
commandInfo,
runspace);
this.DisplayString = "function " + symbolReference.SymbolName;
}
else if (symbolReference.SymbolType == SymbolType.Parameter)
{
// TODO: Get parameter help
this.DisplayString = "(parameter) " + symbolReference.SymbolName;
}
else if (symbolReference.SymbolType == SymbolType.Variable)
{
this.DisplayString = symbolReference.SymbolName;
}
}
示例10: EmbeddableRunspace
public EmbeddableRunspace(NotifyPSHostExit notifyPSHostExit)
{
this.embeddedPSHost = new EmbeddablePSHost(notifyPSHostExit);
this.runspace = RunspaceFactory.CreateRunspace(embeddedPSHost);
this.runspace.Open();
RunScript("Add-PsSnapin LabLauncherTunnel");
}
示例11: RemotePipeline
/// <summary>
/// Private constructor that does most of the work constructing a remote pipeline object.
/// </summary>
/// <param name="runspace">RemoteRunspace object</param>
/// <param name="addToHistory">AddToHistory</param>
/// <param name="isNested">IsNested</param>
private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested)
: base(runspace)
{
_addToHistory = addToHistory;
_isNested = isNested;
_isSteppable = false;
_runspace = runspace;
_computerName = ((RemoteRunspace)_runspace).ConnectionInfo.ComputerName;
_runspaceId = _runspace.InstanceId;
//Initialize streams
_inputCollection = new PSDataCollection<object>();
_inputCollection.ReleaseOnEnumeration = true;
_inputStream = new PSDataCollectionStream<object>(Guid.Empty, _inputCollection);
_outputCollection = new PSDataCollection<PSObject>();
_outputStream = new PSDataCollectionStream<PSObject>(Guid.Empty, _outputCollection);
_errorCollection = new PSDataCollection<ErrorRecord>();
_errorStream = new PSDataCollectionStream<ErrorRecord>(Guid.Empty, _errorCollection);
// Create object stream for method executor objects.
MethodExecutorStream = new ObjectStream();
IsMethodExecutorStreamEnabled = false;
SetCommandCollection(_commands);
//Create event which will be signalled when pipeline execution
//is completed/failed/stoped.
//Note:Runspace.Close waits for all the running pipeline
//to finish. This Event must be created before pipeline is
//added to list of running pipelines. This avoids the race condition
//where Close is called after pipeline is added to list of
//running pipeline but before event is created.
PipelineFinishedEvent = new ManualResetEvent(false);
}
示例12: HookInjection
public HookInjection(
RemoteHooking.IContext InContext,
String InChannelName,
String entryPoint,
String dll,
String returnType,
String scriptBlock,
String modulePath,
String additionalCode,
bool eventLog)
{
Log("Opening hook interface channel...", eventLog);
Interface = RemoteHooking.IpcConnectClient<HookInterface>(InChannelName);
try
{
Runspace = RunspaceFactory.CreateRunspace();
Runspace.Open();
//Runspace.SessionStateProxy.SetVariable("HookInterface", Interface);
}
catch (Exception ex)
{
Log("Failed to open PowerShell runspace." + ex.Message, eventLog);
Interface.ReportError(RemoteHooking.GetCurrentProcessId(), ex);
}
}
示例13: Dispose
/// <summary>
/// Disposes the RunspaceHandle once the holder is done using it.
/// Causes the handle to be released back to the PowerShellContext.
/// </summary>
public void Dispose()
{
// Release the handle and clear the runspace so that
// no further operations can be performed on it.
this.powerShellContext.ReleaseRunspaceHandle(this);
this.Runspace = null;
}
示例14: WishModel
public WishModel()
{
_runspace = RunspaceFactory.CreateRunspace();
_runspace.Open();
_runner = new Powershell(_runspace);
_repl = new Repl(_runner);
}
示例15: createRunspace
private bool createRunspace(string command)
{
bool result = false;
// 20131210
// UIAutomation.Preferences.FromCache = false;
try {
testRunSpace = null;
testRunSpace = RunspaceFactory.CreateRunspace();
testRunSpace.Open();
Pipeline cmd =
testRunSpace.CreatePipeline(command);
cmd.Invoke();
result = true;
}
catch (Exception eInitRunspace) {
richResults.Text += eInitRunspace.Message;
richResults.Text += "\r\n";
result = false;
}
return result;
//Screen.PrimaryScreen.Bounds.Width
}