本文整理汇总了C#中System.Management.Automation.PSCommand.AddScript方法的典型用法代码示例。如果您正苦于以下问题:C# PSCommand.AddScript方法的具体用法?C# PSCommand.AddScript怎么用?C# PSCommand.AddScript使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Management.Automation.PSCommand
的用法示例。
在下文中一共展示了PSCommand.AddScript方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Create
public PSSession Create(string userName, SecureString password, string connectionUri, string schemauri, Action<PSDataStreams> psDataStreamAction)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentOutOfRangeException("userName");
}
if (password == null)
{
throw new ArgumentOutOfRangeException("password");
}
if (string.IsNullOrEmpty(connectionUri))
{
throw new ArgumentOutOfRangeException("connectionUri");
}
this.runspace.SetCredentialVariable(userName, password);
var command = new PSCommand();
string importpssessionscript = Constants.SessionScripts.NewPSSessionScriptWithBasicAuth;
if (AllowRedirection) importpssessionscript += Constants.SessionScripts.AllowRedirectionInNewPSSession;
command.AddScript(string.Format(importpssessionscript, schemauri, connectionUri));
Collection<PSSession> sessions = this.runspace.ExecuteCommand<PSSession>(command, psDataStreamAction);
if (sessions.Count > 0) this.runspace.SetRunspaceVariable(Constants.ParameterNameStrings.Session, sessions[0]);
return sessions.Count == 0 ? null : sessions[0];
}
示例2: assignPhoto
public void assignPhoto(string login, string fileLocation)
{
using (var context = new PrincipalContext(ContextType.Domain, Form1._Domain, Form1._AdminUser, Form1._Password))
{
//Import-RecipientDataProperty -Identity "Scott Carter" -Picture -FileData ([Byte[]]$(Get-Content -Path "C:\StaffPhotos\DJScott1.jpg" -Encoding Byte -ReadCount 0))
PowerShell powershell = PowerShell.Create();
powershell.Runspace = getRunspace();
PSCommand command = new PSCommand();
command.AddScript("Import-RecipientDataProperty -Identity " + '\u0022' + myAD.GetAccountName(login) + '\u0022' + " -Picture -FileData ([Byte[]]$(Get-Content -Path " + '\u0022' + fileLocation + '\u0022' + " -Encoding Byte -ReadCount 0))");
powershell.Commands = command;
try
{
Collection<PSObject> commandResults = powershell.Invoke<PSObject>();
foreach (PSObject result in commandResults)
{
Form1.myForm.lblExchMessage.Text = result.ToString();
Form1.myForm.lblExchMessage.Visible = true;
}
}
catch (Exception e)
{
Form1.myForm.lblExchMessage.Text = e.Message;
Form1.myForm.lblExchMessage.Visible = true;
}
finally
{
powershell.Dispose();
}
}
}
示例3: CanExecutePSCommand
public async Task CanExecutePSCommand()
{
PSCommand psCommand = new PSCommand();
psCommand.AddScript("$a = \"foo\"; $a");
var executeTask =
this.powerShellContext.ExecuteCommand<string>(psCommand);
await this.AssertStateChange(PowerShellContextState.Running);
await this.AssertStateChange(PowerShellContextState.Ready);
var result = await executeTask;
Assert.Equal("foo", result.First());
}
示例4: CanQueueParallelRunspaceRequests
public async Task CanQueueParallelRunspaceRequests()
{
// Concurrently initiate 4 requests in the session
this.powerShellContext.ExecuteScriptString("$x = 100");
Task<RunspaceHandle> handleTask = this.powerShellContext.GetRunspaceHandle();
this.powerShellContext.ExecuteScriptString("$x += 200");
this.powerShellContext.ExecuteScriptString("$x = $x / 100");
PSCommand psCommand = new PSCommand();
psCommand.AddScript("$x");
Task<IEnumerable<int>> resultTask = this.powerShellContext.ExecuteCommand<int>(psCommand);
// Wait for the requested runspace handle and then dispose it
RunspaceHandle handle = await handleTask;
handle.Dispose();
// At this point, the remaining command executions should execute and complete
int result = (await resultTask).FirstOrDefault();
// 100 + 200 = 300, then divided by 100 is 3. We are ensuring that
// the commands were executed in the sequence they were called.
Assert.Equal(3, result);
}
示例5: HandleExpandAliasRequest
private async Task HandleExpandAliasRequest(
string content,
RequestContext<string> requestContext)
{
var script = @"
function __Expand-Alias {
param($targetScript)
[ref]$errors=$null
$tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) |
Sort Start -Descending
foreach ($token in $tokens) {
$definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition
if($definition) {
$lhs=$targetScript.Substring(0, $token.Start)
$rhs=$targetScript.Substring($token.Start + $token.Length)
$targetScript=$lhs + $definition + $rhs
}
}
$targetScript
}";
var psCommand = new PSCommand();
psCommand.AddScript(script);
await this.editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand);
psCommand = new PSCommand();
psCommand.AddCommand("__Expand-Alias").AddArgument(content);
var result = await this.editorSession.PowerShellContext.ExecuteCommand<string>(psCommand);
await requestContext.SendResult(result.First().ToString());
}
示例6: CreatePsCommandNotOverriden
private PSCommand CreatePsCommandNotOverriden(string line, bool isScript, bool? useNewScope)
{
PSCommand command = new PSCommand();
if (isScript)
{
if (useNewScope.HasValue)
{
command.AddScript(line, useNewScope.Value);
return command;
}
command.AddScript(line);
return command;
}
if (useNewScope.HasValue)
{
command.AddCommand(line, useNewScope.Value);
return command;
}
command.AddCommand(line);
return command;
}
示例7: HandlePromptCommand
protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection<PSObject> output)
{
// Nested debugged runspace prompt should look like:
// [ComputerName]: [DBG]: [Process:<id>]: [RunspaceName]: PS C:\>
string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null;
string processPartPattern = "{0}[{1}:{2}]:{3}";
string processPart = StringUtil.Format(processPartPattern,
@"""",
DebuggerStrings.NestedRunspaceDebuggerPromptProcessName,
@"$($PID)",
@"""");
string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """;
string promptScript = "'[DBG]: '" + " + " + processPart + " + " + "' [" + CodeGeneration.EscapeSingleQuotedStringContent(_runspace.Name) + "]: '" + " + " + locationPart;
// Get the command prompt from the wrapped debugger.
PSCommand promptCommand = new PSCommand();
promptCommand.AddScript(promptScript);
PSDataCollection<PSObject> promptOutput = new PSDataCollection<PSObject>();
_wrappedDebugger.ProcessCommand(promptCommand, promptOutput);
string promptString = (promptOutput.Count == 1) ? promptOutput[0].BaseObject as string : string.Empty;
var nestedPromptString = new System.Text.StringBuilder();
// For remote runspaces display computer name in prompt.
if (!string.IsNullOrEmpty(computerName))
{
nestedPromptString.Append("[" + computerName + "]:");
}
nestedPromptString.Append(promptString);
// Fix up for non-remote runspaces since the runspace is not in a nested prompt
// but the root runspace is.
if (string.IsNullOrEmpty(computerName))
{
nestedPromptString.Insert(nestedPromptString.Length - 1, ">");
}
output.Add(nestedPromptString.ToString());
return new DebuggerCommandResults(null, true);
}
示例8: DebuggerOnDebuggerStop
private void DebuggerOnDebuggerStop(object sender, DebuggerStopEventArgs args)
{
Debugger debugger = sender as Debugger;
DebuggerResumeAction? resumeAction = null;
DebuggingInBreakpoint = true;
try
{
if (
((ScriptingHostUserInterface) host.UI).CheckSessionCanDoInteractiveAction(
nameof(DebuggerOnDebuggerStop)))
{
var output = new PSDataCollection<PSObject>();
output.DataAdded += (dSender, dArgs) =>
{
foreach (var item in output.ReadAll())
{
host.UI.WriteLine(item.ToString());
}
};
var message = Message.Parse(this, "ise:breakpointhit");
//var position = args.InvocationInfo.DisplayScriptPosition;
IScriptExtent position;
try
{
position = args.InvocationInfo.GetType()
.GetProperty("ScriptPosition",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty)
.GetValue(args.InvocationInfo) as IScriptExtent;
}
catch (Exception)
{
position = args.InvocationInfo.DisplayScriptPosition;
}
if (position != null)
{
message.Arguments.Add("Line", (position.StartLineNumber - 1).ToString());
message.Arguments.Add("Column", (position.StartColumnNumber - 1).ToString());
message.Arguments.Add("EndLine", (position.EndLineNumber - 1).ToString());
message.Arguments.Add("EndColumn", (position.EndColumnNumber - 1).ToString());
}
else
{
message.Arguments.Add("Line", (args.InvocationInfo.ScriptLineNumber - 1).ToString());
message.Arguments.Add("Column", (args.InvocationInfo.OffsetInLine - 1).ToString());
message.Arguments.Add("EndLine", (args.InvocationInfo.ScriptLineNumber).ToString());
message.Arguments.Add("EndColumn", (0).ToString());
}
message.Arguments.Add("HitCount",
args.Breakpoints.Count > 0 ? args.Breakpoints[0].HitCount.ToString() : "1");
SendUiMessage(message);
while (resumeAction == null && !abortRequested)
{
if (ImmediateCommand != null)
{
var psCommand = new PSCommand();
psCommand.AddScript(ImmediateCommand as string)
.AddCommand("Out-Default");
//.AddParameter("Stream", true);
var results = debugger?.ProcessCommand(psCommand, output);
ImmediateResults = output;
if (results?.ResumeAction != null)
{
resumeAction = results.ResumeAction;
}
ImmediateCommand = null;
}
else
{
Thread.Sleep(20);
}
}
args.ResumeAction = resumeAction ?? DebuggerResumeAction.Continue;
}
}
finally
{
DebuggingInBreakpoint = false;
}
}
示例9: emailForward
public void emailForward(bool cancelForward, string login)
{
using (var context = new PrincipalContext(ContextType.Domain, Form1._Domain, Form1._AdminUser, Form1._Password))
{
PowerShell powershell = PowerShell.Create();
powershell.Runspace = getRunspace();
PSCommand command = new PSCommand();
if (cancelForward)
{ command.AddScript("Set-Mailbox -Identity " + '\u0022' + myAD.GetAccountName(login) + '\u0022' + " -ForwardingAddress $null -DeliverToMailboxAndForward $false"); }
else
{
if (Form1.myForm.cbExchForwardAndKeep.Checked)
{ command.AddScript("Set-Mailbox -Identity " + '\u0022' + myAD.GetAccountName(login) + '\u0022' + " -ForwardingAddress " + '\u0022' + Form1.myForm.tbExchForwardEmailsTo.Text + '\u0022' + " -DeliverToMailboxAndForward $true"); }
else
{ command.AddScript("Set-Mailbox -Identity " + '\u0022' + myAD.GetAccountName(login) + '\u0022' + " -ForwardingAddress " + '\u0022' + Form1.myForm.tbExchForwardEmailsTo.Text + '\u0022'); }
}
powershell.Commands = command;
try
{
Collection<PSObject> commandResults = powershell.Invoke<PSObject>();
if (powershell.Streams.Error.Count > 0)
{
Form1.myForm.lblExchMessage.Text = powershell.Streams.Error.ReadAll().ToString();
Form1.myForm.lblExchMessage.Visible = true;
}
foreach (PSObject result in commandResults)
{
Form1.myForm.lblExchMessage.Text = result.ToString();
Form1.myForm.lblExchMessage.Visible = true;
}
}
catch (Exception e)
{
Form1.myForm.lblExchMessage.Text = e.Message;
Form1.myForm.lblExchMessage.Visible = true;
}
finally
{
powershell.Dispose();
}
}
}
示例10: giveEmailControl
public void giveEmailControl(string mailBox, string nameGettingControl)
{
PowerShell powershell = PowerShell.Create();
powershell.Runspace = getRunspace();
PSCommand command = new PSCommand();
command.AddScript("Get-mailbox -Identity " + '\u0022' + myAD.GetAccountName(mailBox) + '\u0022' + " | Add-MailboxPermission -AccessRights Fullaccess -User " + nameGettingControl);
powershell.Commands = command;
try
{
Collection<PSObject> commandResults = powershell.Invoke<PSObject>();
if (powershell.Streams.Error.Count > 0)
{
Form1.myForm.lblExchMessage.Text = powershell.Streams.Error.ReadAll().ToString();
Form1.myForm.lblExchMessage.Visible = true;
}
foreach (PSObject result in commandResults)
{
Form1.myForm.lblExchMessage.Text = "Full mailbox access granted to: " + nameGettingControl;
Form1.myForm.lblExchMessage.Visible = true;
Form1.myForm._Notes.AppendLine();
Form1.myForm._Notes.Append("Full mailbox access granted to " + nameGettingControl);
}
}
catch (Exception e)
{
Form1.myForm.lblExchMessage.Text = e.Message;
Form1.myForm.lblExchMessage.Visible = true;
Form1.myForm._Notes.AppendLine();
Form1.myForm._Notes.Append("Full mailbox access NOT granted to " + nameGettingControl);
Form1.myForm._Notes.AppendLine();
Form1.myForm._Notes.Append(e.Message);
}
finally
{
powershell.Dispose();
}
}
示例11: HandleDebuggerStopEvent
// Method to handle the Debugger DebuggerStop event.
// The debugger will remain in debugger stop mode until this event
// handler returns, at which time DebuggerStopEventArgs.ResumeAction should
// be set to indicate how the debugger should proceed (Continue, StepInto,
// StepOut, StepOver, Stop).
// This handler should run a REPL (Read Evaluate Print Loop) to allow user
// to investigate the state of script execution, by processing user commands
// with the Debugger.ProcessCommand method. If a user command releases the
// debugger then the DebuggerStopEventArgs.ResumeAction is set and this
// handler returns.
private void HandleDebuggerStopEvent(object sender, DebuggerStopEventArgs args)
{
Debugger debugger = sender as Debugger;
DebuggerResumeAction? resumeAction = null;
// Display messages pertaining to this debugger stop.
WriteDebuggerStopMessages(args);
// Simple REPL (Read Evaluate Print Loop) to process
// Debugger commands.
while (resumeAction == null)
{
// Write debug prompt.
Console.Write("[DBG] PS >> ");
string command = Console.ReadLine();
Console.WriteLine();
// Stream output from command processing to console.
var output = new PSDataCollection<PSObject>();
output.DataAdded += (dSender, dArgs) =>
{
foreach (var item in output.ReadAll())
{
Console.WriteLine(item);
}
};
// Process command.
// The Debugger.ProcesCommand method will parse and handle debugger specific
// commands such as 'h' (help), 'list', 'stepover', etc. If the command is
// not specific to the debugger then it will be evaluated as a PowerShell
// command or script. The returned DebuggerCommandResults object will indicate
// whether the command was evaluated by the debugger and if the debugger should
// be released with a specific resume action.
PSCommand psCommand = new PSCommand();
psCommand.AddScript(command).AddCommand("Out-String").AddParameter("Stream", true);
DebuggerCommandResults results = debugger.ProcessCommand(psCommand, output);
if (results.ResumeAction != null)
{
resumeAction = results.ResumeAction;
}
}
// Return from event handler with user resume action.
args.ResumeAction = resumeAction.Value;
}
示例12: HandleFindModuleRequest
private async Task HandleFindModuleRequest(
object param,
RequestContext<object> requestContext)
{
var psCommand = new PSCommand();
psCommand.AddScript("Find-Module | Select Name, Description");
var modules = await editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand);
var moduleList = new List<PSModuleMessage>();
if (modules != null)
{
foreach (dynamic m in modules)
{
moduleList.Add(new PSModuleMessage { Name = m.Name, Description = m.Description });
}
}
await requestContext.SendResult(moduleList);
}