/// <summary> /// Creates the PSCommand when the runspace is not overridden. /// </summary> private PSCommand CreatePsCommandNotOverridden(string line, bool isScript, bool?useNewScope) { PSCommand command = new PSCommand(); if (isScript) { if (useNewScope.HasValue) { command.AddScript(line, useNewScope.Value); } else { command.AddScript(line); } } else { if (useNewScope.HasValue) { command.AddCommand(line, useNewScope.Value); } else { command.AddCommand(line); } } return(command); }
public static bool Exec(string path, string param = "") { try { string workspace = Path.GetDirectoryName(Path.GetFullPath(path)); string file = Path.GetFileName(path); using (Runspace rs = RunspaceFactory.CreateRunspace()) { rs.Open(); using (PowerShell ps = PowerShell.Create()) { PSCommand pscmd = new PSCommand(); pscmd.AddScript($"cd {workspace}"); pscmd.AddScript($".\\{file} {param}"); ps.Commands = pscmd; ps.Runspace = rs; Log.Logger.Debug($"コマンド:{pscmd.Commands}"); try { var results = ps.Invoke(); if (results.Count() > 0) { Log.Logger.Info("実行スクリプト:" + file); foreach (var res in results) { Log.Logger.Info("実行結果:" + res); } } } catch (PSSecurityException) { Log.Logger.Error("スクリプト実行を許可してください"); Log.Logger.Error("Set-ExecutionPolicy RemoteSigned -Scope CurrentUser"); return(false); } } } } catch (Exception e) { Log.Logger.Error("PowerShellの実行に失敗しました", e); return(false); } return(true); }
private void RegisterPSEditFunction(RunspaceDetails runspaceDetails) { if (runspaceDetails.Location == RunspaceLocation.Remote && runspaceDetails.Context == RunspaceContext.Original) { try { runspaceDetails.Runspace.Events.ReceivedEvents.PSEventReceived += HandlePSEventReceivedAsync; PSCommand createCommand = new PSCommand(); createCommand .AddScript(CreatePSEditFunctionScript) .AddParameter("PSEditModule", PSEditModule); if (runspaceDetails.Context == RunspaceContext.DebuggedRunspace) { this.powerShellContext.ExecuteCommandAsync(createCommand).Wait(); } else { using (var powerShell = System.Management.Automation.PowerShell.Create()) { powerShell.Runspace = runspaceDetails.Runspace; powerShell.Commands = createCommand; powerShell.Invoke(); } } } catch (RemoteException e) { this.logger.LogException("Could not create psedit function.", e); } } }
static void Main(string[] args) { string uname = Console.ReadLine(); string pwd = Console.ReadLine(); PSCommand psCommand = new PSCommand(); psCommand.AddScript("$PSHome"); PowerShell ps = PowerShell.Create(); ps.Commands = psCommand; Collection <PSObject> results = ps.Invoke(); Console.WriteLine("results length::" + results.Count); foreach (PSObject res in results) { Console.WriteLine("Res val::" + res.ToString()); } Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); ps.Runspace = runspace; results = ps.Invoke(); Console.WriteLine("results length::" + results.Count); foreach (PSObject res in results) { Console.WriteLine("Res val::" + res.ToString()); } PSCommand rmcommand = new PSCommand(); string exchangeUri = "https://outlook.office365.com/powershell-liveid/"; Uri uri = new Uri(exchangeUri); rmcommand.AddCommand("New-PSSession"); rmcommand.AddParameter("ConfigurationName", "Microsoft.Exchange"); rmcommand.AddParameter("ConnectionUri", uri); SecureString password = new SecureString(); foreach (char c in pwd) { password.AppendChar(c); } PSCredential creds = new PSCredential(uname, password); rmcommand.AddParameter("Credential", creds); rmcommand.AddParameter("Authentication", "Basic"); rmcommand.AddParameter("AllowRedirection"); ps.Commands = rmcommand; Collection <PSObject> result = ps.Invoke(); Console.ReadLine(); }
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); }
/// <summary> /// Process the PowerShell /// Obtains the PowerShell session per config and then invokes the script /// </summary> private void ProcessScript() { try { PowerShell powershell = PowerShell.Create(); powershell.Runspace = _exchangeRunspace; // Apply any credentials we have to the runspace _variablesManager.ApplyCredentialsToPowerShell(powershell); if (checkBoxProcessAsCommand.Checked) { // If we connect directly to the Exchange remote runspace, we can't run a script. Each command (which // must be an Exchange cmdlet) must be added individually. for (int i = 0; i < textBoxPowerShell.Lines.Count <string>(); i++) { powershell.Commands = ParseCommand(textBoxPowerShell.Lines[i]); InvokeAndReport(powershell); } } else { // This method will only work when we import the remote Exchange runspace into the local runspace. // In this case, FullLanguage is available in the local session, and only Exchange cmdlets are sent to the remote. PSCommand command = new PSCommand(); command.AddScript(textBoxPowerShell.Text); powershell.Commands = command; InvokeAndReport(powershell); } } catch (Exception ex) { LogError(ex.Message); } }
private async Task FetchStackFrames() { var psCommand = new PSCommand(); psCommand.AddScript("return Get-PSCallStack"); var results = await ExecuteCommand <CallStackFrame>(psCommand); var callStackFrames = results.ToArray(); var stackFrameDetails = new List <StackFrameDetails>(); //_stackFrameDetails = new StackFrameDetails[callStackFrames.Length]; for (var i = 0; i < callStackFrames.Length; i++) { var autoVariables = new VariableContainerDetails( VariableContainerDetails.AutoVariablesName); _variables.Add(autoVariables); try { var localVariables = await FetchVariableContainer(i.ToString(), autoVariables); stackFrameDetails.Add( StackFrameDetails.Create(callStackFrames[i], autoVariables, localVariables)); } catch (Exception) { } } _stackFrameDetails = stackFrameDetails.ToArray(); }
/// <summary> /// Executes a script string in the session's runspace. /// </summary> /// <param name="scriptString">The script string to execute.</param> /// <returns>A Task that can be awaited for the script completion.</returns> public async Task <IEnumerable <object> > ExecuteScriptString(string scriptString) { PSCommand psCommand = new PSCommand(); psCommand.AddScript(scriptString); return(await this.ExecuteCommand <object>(psCommand, true)); }
/// <summary> /// Gets the PSCommand that gathers details from the /// current session. /// </summary> /// <returns>A PSCommand used to gather session details.</returns> public static PSCommand GetDetailsCommand() { PSCommand infoCommand = new PSCommand(); infoCommand.AddScript( "@{ 'computerName' = $env:ComputerName; 'processId' = $PID; 'instanceId' = $host.InstanceId }"); return(infoCommand); }
/// <summary> /// Gets the PSCommand that gathers details from the /// current session. /// </summary> /// <returns>A PSCommand used to gather session details.</returns> public static PSCommand GetDetailsCommand() { PSCommand infoCommand = new PSCommand(); infoCommand.AddScript( "@{ 'computerName' = if ([Environment]::MachineName) {[Environment]::MachineName} else {'localhost'}; 'processId' = $PID; 'instanceId' = $host.InstanceId }"); return(infoCommand); }
private static void RunScriptMethod4(string scriptText) { //M-II //Microsoft.PowerShell.SDK for resolving exception PSCredential creds = new PSCredential("myfirstvm", StringToSecureString("tE&sJk8c&gqG")); System.Uri uri = new Uri("http://Exchange-Server/powershell?serializationLevel=Full"); Runspace runspace = RunspaceFactory.CreateRunspace(); PowerShell powershell = PowerShell.Create(); PSCommand command = new PSCommand(); command.AddCommand("New-PSSession"); command.AddParameter("ConfigurationName", "Microsoft.Exchange"); command.AddParameter("ConnectionUri", uri); command.AddParameter("Credential", creds); command.AddParameter("Authentication", "Default"); powershell.Commands = command; runspace.Open(); powershell.Runspace = runspace; Collection <PSSession> result = powershell.Invoke <PSSession>(); if (result.Count > 0) { // We use a string builder ton create our result text var builder = new StringBuilder(); foreach (var psObject in result) { // Convert the Base Object to a string and append it to the string builder. // Add \r\n for line breaks builder.Append(psObject.ToString() + "\r\n"); } // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < > //var text = IServer.HtmlEncode(builder.ToString()); } powershell = PowerShell.Create(); command = new PSCommand(); command.AddCommand("Set-Variable"); command.AddParameter("Name", "ra"); command.AddParameter("Value", result[0]); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); powershell = PowerShell.Create(); command = new PSCommand(); command.AddScript("Import-PSSession -Session $ra"); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); }
public PSCommand Create() { var scriptFilePath = ResolveFilePath(); var command = new PSCommand(); command.AddScript(scriptFilePath); return(command); }
private async Task FetchStackFramesAsync(string scriptNameOverride) { PSCommand psCommand = new PSCommand(); // This glorious hack ensures that Get-PSCallStack returns a list of CallStackFrame // objects (or "deserialized" CallStackFrames) when attached to a runspace in another // process. Without the intermediate variable Get-PSCallStack inexplicably returns // an array of strings containing the formatted output of the CallStackFrame list. var callStackVarName = $"$global:{PsesGlobalVariableNamePrefix}CallStack"; psCommand.AddScript($"{callStackVarName} = Get-PSCallStack; {callStackVarName}"); var results = await this.powerShellContext.ExecuteCommandAsync <PSObject>(psCommand).ConfigureAwait(false); var callStackFrames = results.ToArray(); this.stackFrameDetails = new StackFrameDetails[callStackFrames.Length]; for (int i = 0; i < callStackFrames.Length; i++) { VariableContainerDetails autoVariables = new VariableContainerDetails( this.nextVariableId++, VariableContainerDetails.AutoVariablesName); this.variables.Add(autoVariables); VariableContainerDetails localVariables = await FetchVariableContainerAsync(i.ToString(), autoVariables).ConfigureAwait(false); // When debugging, this is the best way I can find to get what is likely the workspace root. // This is controlled by the "cwd:" setting in the launch config. string workspaceRootPath = this.powerShellContext.InitialWorkingDirectory; this.stackFrameDetails[i] = StackFrameDetails.Create(callStackFrames[i], autoVariables, localVariables, workspaceRootPath); string stackFrameScriptPath = this.stackFrameDetails[i].ScriptPath; if (scriptNameOverride != null && string.Equals(stackFrameScriptPath, StackFrameDetails.NoFileScriptPath)) { this.stackFrameDetails[i].ScriptPath = scriptNameOverride; } else if (this.powerShellContext.CurrentRunspace.Location == RunspaceLocation.Remote && this.remoteFileManager != null && !string.Equals(stackFrameScriptPath, StackFrameDetails.NoFileScriptPath)) { this.stackFrameDetails[i].ScriptPath = this.remoteFileManager.GetMappedPath( stackFrameScriptPath, this.powerShellContext.CurrentRunspace); } } }
private DebuggerCommandResults HandlePromptCommand(PSDataCollection <PSObject> output) { // Nested debugged runspace prompt should look like: // [DBG]: [JobName]: PS C:\>> string promptScript = "'[DBG]: '" + " + " + "'[" + CodeGeneration.EscapeSingleQuotedStringContent(_jobName) + "]: '" + " + " + @"""PS $($executionContext.SessionState.Path.CurrentLocation)>> """; PSCommand promptCommand = new PSCommand(); promptCommand.AddScript(promptScript); _wrappedDebugger.ProcessCommand(promptCommand, output); return(new DebuggerCommandResults(null, true)); }
private void ConnectToExchange(PowerShell powershell, Runspace runspace) { PSCommand command = new PSCommand(); // We get errors when the Exchange remote script tries to talk to us, // unless we redefine Write-Host to be an empty script. command.AddScript("Function Write-Host {}"); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); // Load the Exchange Management Shell startup script command = new PSCommand(); command.AddScript(RemoteExchangeScript); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); // Ask Exchange Management Shell to sniff the environment for a server and give us a session command = new PSCommand(); command.AddCommand("Connect-ExchangeServer"); command.AddParameter("Auto"); powershell.Commands = command; powershell.Invoke(); // Dealing with the possibility I might error connecting to one server, // but then succeed connecting to the next bool connected = false; foreach (VerboseRecord vr in powershell.Streams.Verbose) { if (vr.Message.StartsWith("Connected to")) { connected = true; break; } } if (!connected && powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); }
private PSDataCollection <PSObject> ExecuteDebuggingCommand() { PSCommand psCommand = new PSCommand(); psCommand.AddScript(_debuggingCommand); psCommand.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); var output = new PSDataCollection <PSObject>(); output.DataAdded += objects_DataAdded; _runspace.Debugger.ProcessCommand(psCommand, output); return(output); }
private void RefreshScopedVariable40() { ServiceCommon.Log("Debuggger stopped, let us retreive all local variable in scope"); if (_runspace.ConnectionInfo != null) { PSCommand psCommand = new PSCommand(); psCommand.AddScript("Get-Variable"); var output = new PSDataCollection <PSObject>(); DebuggerCommandResults results = _runspace.Debugger.ProcessCommand(psCommand, output); _varaiables = output; } else { RefreshScopedVariable(); } }
private void RefreshCallStack40() { ServiceCommon.Log("Debuggger stopped, let us retreive all call stack frames"); if (_runspace.ConnectionInfo != null) { PSCommand psCommand = new PSCommand(); psCommand.AddScript("Get-PSCallstack"); var output = new PSDataCollection <PSObject>(); DebuggerCommandResults results = _runspace.Debugger.ProcessCommand(psCommand, output); _callstack = output; } else { RefreshCallStack(); } }
private Collection <PSObject> PSExecute(string Script) { try { PowerShell powershell = PowerShell.Create(); PSCommand command = new PSCommand(); powershell = PowerShell.Create(); command = new PSCommand(); command.AddScript(Script); powershell.Commands = command; powershell.Runspace = runspace; Collection <PSObject> results = new Collection <PSObject>(); results = powershell.Invoke(); foreach (ErrorRecord current in powershell.Streams.Error) { AppendMainText("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nPSExecute error start\n"); AppendMainText("Exception: " + current.Exception.ToString() + "\n"); AppendMainText("Inner Exception: " + current.Exception.InnerException + "\n"); AppendMainText("PSExecute error end\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); return(null); } return(results); } catch (Exception ex) { AppendMainText("Following exception happened when calling PS command:\n"); AppendMainText("Exception: " + ex.Message.ToString()); return(null); } finally { // dispose the runspace and enable garbage collection // runspace.Dispose(); // runspace = null; // Finally dispose the powershell and set all variables to null to free // up any resources. //powershell.Dispose(); // powershell = null; } }
// 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; }
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()); }
/// <summary> /// Saves the contents of the file under the temporary local /// file cache to its corresponding remote file. /// </summary> /// <param name="localFilePath"> /// The local file whose contents will be saved. It is assumed /// that the editor has saved the contents of the local cache /// file to disk before this method is called. /// </param> /// <returns>A Task to be awaited for completion.</returns> public async Task SaveRemoteFile(string localFilePath) { string remoteFilePath = this.GetMappedPath( localFilePath, this.powerShellContext.CurrentRunspace); this.logger.Write( LogLevel.Verbose, $"Saving remote file {remoteFilePath} (local path: {localFilePath})"); byte[] localFileContents = null; try { localFileContents = File.ReadAllBytes(localFilePath); } catch (IOException e) { this.logger.WriteException( "Failed to read contents of local copy of remote file", e); return; } PSCommand saveCommand = new PSCommand(); saveCommand .AddScript(SetRemoteContentsScript) .AddParameter("RemoteFilePath", remoteFilePath) .AddParameter("Content", localFileContents); StringBuilder errorMessages = new StringBuilder(); await this.powerShellContext.ExecuteCommand <object>( saveCommand, errorMessages, false, false); if (errorMessages.Length > 0) { this.logger.Write(LogLevel.Error, $"Remote file save failed due to an error:\r\n\r\n{errorMessages}"); } }
/// <summary> /// Executes a script string in the session's runspace. /// </summary> /// <param name="scriptString">The script string to execute.</param> /// <param name="writeInputToHost">If true, causes the script string to be written to the host.</param> /// <param name="writeOutputToHost">If true, causes the script output to be written to the host.</param> /// <returns>A Task that can be awaited for the script completion.</returns> public async Task <IEnumerable <object> > ExecuteScriptString( string scriptString, bool writeInputToHost, bool writeOutputToHost) { if (writeInputToHost) { this.WriteOutput( scriptString + Environment.NewLine, true); } PSCommand psCommand = new PSCommand(); psCommand.AddScript(scriptString); return(await this.ExecuteCommand <object>(psCommand, writeOutputToHost)); }
/// <summary> /// Executes a script file at the specified path. /// </summary> /// <param name="scriptPath">The path to the script file to execute.</param> /// <param name="arguments">Arguments to pass to the script.</param> /// <returns>A Task that can be awaited for completion.</returns> public async Task ExecuteScriptAtPath(string scriptPath, string arguments = null) { // If we don't escape wildcard characters in the script path, the script can // fail to execute if say the script name was foo][.ps1. // Related to issue #123. string escapedScriptPath = EscapeWildcardsInPath(scriptPath); if (arguments != null) { escapedScriptPath += " " + arguments; } PSCommand command = new PSCommand(); command.AddScript(escapedScriptPath); await this.ExecuteCommand <object>(command, true); }
public async Task CanRegisterAndInvokeCommandWithScriptBlock() { await extensionService.PowerShellContext.ExecuteScriptStringAsync( "Register-EditorCommand -Name \"test.scriptblock\" -DisplayName \"ScriptBlock extension\" -ScriptBlock { $global:extensionValue = 10 }"); // Wait for the add event EditorCommand command = await this.AssertExtensionEvent(EventType.Add, "test.scriptblock"); // Invoke the command await extensionService.InvokeCommandAsync("test.scriptblock", this.commandContext); // Assert the expected value PSCommand psCommand = new PSCommand(); psCommand.AddScript("$global:extensionValue"); var results = await powerShellContext.ExecuteCommandAsync <int>(psCommand); Assert.Equal(10, results.FirstOrDefault()); }
private DebuggerCommandResults RunDebuggerCommand(Debugger debugger, string command) { var output = new PSDataCollection <PSObject>(); output.DataAdded += (dSender, dArgs) => { foreach (var item in output.ReadAll()) { UserIOImpl.PrintMessage(item.ToString() + "\n"); } }; PSCommand psCommand = new PSCommand(); psCommand.AddScript(command); DebuggerCommandResults results = debugger.ProcessCommand(psCommand, output); return(results); }
/// <summary> /// Opens the script a remote process is running. /// </summary> /// <param name="scriptName"></param> /// <returns></returns> private string OpenRemoteAttachedFile(string scriptName) { if (!_needToCopyRemoteScript && _mapRemoteToLocal.ContainsKey(scriptName)) { return(_mapRemoteToLocal[scriptName]); } PSCommand psCommand = new PSCommand(); psCommand.AddScript(string.Format("Get-Content \"{0}\"", scriptName)); PSDataCollection <PSObject> result = new PSDataCollection <PSObject>(); _runspace.Debugger.ProcessCommand(psCommand, result); string[] remoteText = new string[result.Count()]; for (int i = 0; i < remoteText.Length; i++) { remoteText[i] = result.ElementAt(i).BaseObject as string; } // create new directory and corressponding file path/name string tmpFileName = Path.GetTempFileName(); string dirPath = tmpFileName.Remove(tmpFileName.LastIndexOf('.')); string fullFileName = Path.Combine(dirPath, new FileInfo(scriptName).Name); // check to see if we have already copied the script over, and if so, overwrite if (_mapRemoteToLocal.ContainsKey(scriptName)) { fullFileName = _mapRemoteToLocal[scriptName]; } else { Directory.CreateDirectory(dirPath); } _mapRemoteToLocal[scriptName] = fullFileName; _mapLocalToRemote[fullFileName] = scriptName; File.WriteAllLines(fullFileName, remoteText); return(fullFileName); }
public List <UserGroupResult> GetUserGroup(string alias) { var ret = new List <UserGroupResult>(); var runspace = this.CreateRunspace(); var powershell = PowerShell.Create(); var command = new PSCommand(); var script = "Get-DistributionGroup -ResultSize unlimited -Filter \"Members - like \"\"$((Get - Mailbox " + alias + ").DistinguishedName)\"\"\" |fl name,PrimarySmtpAddress,RequireSenderAuthenticationEnabled,AcceptMessagesOnlyFrom"; command.AddScript(script); powershell.Commands = command; try { runspace.Open(); powershell.Runspace = runspace; Collection <PSObject> results = powershell.Invoke(); if (results != null) { foreach (var psobj in results) { var log = new UserGroupResult(); log.Name = psobj.Properties["Name"].Value.ToString(); log.PrimarySmtpAddress = psobj.Properties["PrimarySmtpAddress"].Value.ToString(); log.RequireSenderAuthenticationEnabled = psobj.Properties["RequireSenderAuthenticationEnabled"].Value.ToString(); log.AcceptMessagesOnlyFrom = psobj.Properties["AcceptMessagesOnlyFrom"].Value.ToString(); ret.Add(log); } } } catch (Exception ex) { this._log.Error("获取用户分组失败", ex); } finally { runspace.Dispose(); powershell.Dispose(); } return(ret); }
public CommandResult RemoveManagedBy(string groupname, string alias) { var ret = new CommandResult(); var runspace = this.CreateRunspace(); var powershell = PowerShell.Create(); var command = new PSCommand(); var script = "Set-DistributionGroup " + groupname + " -ManagedBy " + "@{Remove=\"" + alias + "\"}"; command.AddScript(script); powershell.Commands = command; try { runspace.Open(); powershell.Runspace = runspace; Collection <PSObject> results = powershell.Invoke(); if (results != null) { var users = this.GetManagedBy(groupname); ret.Success = !users.Contains(this.UserInfo(alias).Name); ret.Message = "移除管理员" + (ret.Success ? "成功" : "失败"); } return(ret); } catch (Exception ex) { return(new CommandResult() { Success = false, Message = $"消息:{ex.Message} 堆栈:{ex.StackTrace}" }); } finally { runspace.Dispose(); runspace = null; powershell.Dispose(); powershell = null; } }
public async Task <ExpandAliasResult> Handle(ExpandAliasParams request, CancellationToken cancellationToken) { const string script = @" function __Expand-Alias { param($targetScript) [ref]$errors=$null $tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) | Sort-Object 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 }"; // TODO: Refactor to not rerun the function definition every time. var psCommand = new PSCommand(); psCommand .AddScript(script) .AddStatement() .AddCommand("__Expand-Alias") .AddArgument(request.Text); var result = await _powerShellContextService.ExecuteCommandAsync <string>( psCommand, cancellationToken : cancellationToken).ConfigureAwait(false); return(new ExpandAliasResult { Text = result.First() }); }
/// <summary> /// Creates the PSCommand when the runspace is not overridden /// </summary> private PSCommand CreatePsCommandNotOverriden(string line, bool isScript, bool? useNewScope) { PSCommand command = new PSCommand(); if (isScript) { if (useNewScope.HasValue) { command.AddScript(line, useNewScope.Value); } else { command.AddScript(line); } } else { if (useNewScope.HasValue) { command.AddCommand(line, useNewScope.Value); } else { command.AddCommand(line); } } return command; }