Example #1
0
        public async Task<IEnumerable<VMItem>> GetVMListAsync(string name)
        {
            var psCommand = new PSCommand
            {
                Commands = new List<Command>()
            };

            if (!String.IsNullOrEmpty(vmmServerName))
            {
                psCommand.Commands.Add(new Command(String.Format("$Cloud = Get-SCCloud -Name \"{0}\" -VMMServer \"{1}\"", name, vmmServerName), true));
                psCommand.Commands.Add(new Command("Get-SCVirtualMachine -Cloud $Cloud", true));

                //command = String.Concat(String.Format("$Cloud = Get-SCCloud -Name \"{0}\" -VMMServer \"{1}\"", name, vmmServerName), Environment.NewLine, "Get-SCVirtualMachine -Cloud $Cloud");
            }
            else
            {
                psCommand.ScriptCommand = String.Format("Get-SCVirtualMachine -VMMServer \"{0}\"", name);
            }

            var objects = await psProvider.ExecuteAsync<PSObject>(psCommand);
            if (!String.IsNullOrEmpty(psProvider.Error))
            {
                throw new Exception(psProvider.Error);
            }

            var mapper = new PSMapper();
            return objects.Select(mapper.Map);
        }
Example #2
0
        public async Task<IEnumerable<VMItem>> GetVMListAsync(string name)
        {
            var command = new PSCommand { ScriptCommand = String.Format("Get-Service -ComputerName {0}", name) };
            
            var objects = await psProvider.ExecuteAsync<PSObject>(command);

            var mapper = new TestMapper();
            return objects.Select(mapper.Map);
        }
Example #3
0
        public override string ReadLine(CancellationToken cancellationToken)
        {
            string            inputBeforeCompletion = null;
            string            inputAfterCompletion  = null;
            CommandCompletion currentCompletion     = null;

            int historyIndex = -1;
            IReadOnlyList <PSObject> currentHistory = null;

            StringBuilder inputLine = new();

            int initialCursorCol = Console.CursorLeft;
            int initialCursorRow = Console.CursorTop;

            int currentCursorIndex = 0;

            Console.TreatControlCAsInput = true;

            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    ConsoleKeyInfo keyInfo = ReadKey(cancellationToken);

                    // Do final position calculation after the key has been pressed
                    // because the window could have been resized before then
                    int promptStartCol = initialCursorCol;
                    int promptStartRow = initialCursorRow;
                    int consoleWidth   = Console.WindowWidth;

                    switch (keyInfo.Key)
                    {
                    case ConsoleKey.Tab:
                        if (currentCompletion is null)
                        {
                            inputBeforeCompletion = inputLine.ToString();
                            inputAfterCompletion  = null;

                            // TODO: This logic should be moved to AstOperations or similar!

                            if (_psesHost.DebugContext.IsStopped)
                            {
                                PSCommand command = new PSCommand()
                                                    .AddCommand("TabExpansion2")
                                                    .AddParameter("InputScript", inputBeforeCompletion)
                                                    .AddParameter("CursorColumn", currentCursorIndex)
                                                    .AddParameter("Options", null);

                                currentCompletion = _psesHost.InvokePSCommand <CommandCompletion>(command, executionOptions: null, cancellationToken).FirstOrDefault();
                            }
                            else
                            {
                                currentCompletion = _psesHost.InvokePSDelegate(
                                    "Legacy readline inline command completion",
                                    executionOptions: null,
                                    (pwsh, _) => CommandCompletion.CompleteInput(inputAfterCompletion, currentCursorIndex, options: null, pwsh),
                                    cancellationToken);

                                if (currentCompletion.CompletionMatches.Count > 0)
                                {
                                    int replacementEndIndex =
                                        currentCompletion.ReplacementIndex +
                                        currentCompletion.ReplacementLength;

                                    inputAfterCompletion =
                                        inputLine.ToString(
                                            replacementEndIndex,
                                            inputLine.Length - replacementEndIndex);
                                }
                                else
                                {
                                    currentCompletion = null;
                                }
                            }
                        }

                        CompletionResult completion =
                            currentCompletion?.GetNextResult(
                                !keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift));

                        if (completion is not null)
                        {
                            currentCursorIndex =
                                InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    completion.CompletionText + inputAfterCompletion,
                                    currentCursorIndex,
                                    insertIndex: currentCompletion.ReplacementIndex,
                                    replaceLength: inputLine.Length - currentCompletion.ReplacementIndex,
                                    finalCursorIndex: currentCompletion.ReplacementIndex + completion.CompletionText.Length);
                        }

                        continue;

                    case ConsoleKey.LeftArrow:
                        currentCompletion = null;

                        if (currentCursorIndex > 0)
                        {
                            currentCursorIndex =
                                MoveCursorToIndex(
                                    promptStartCol,
                                    promptStartRow,
                                    consoleWidth,
                                    currentCursorIndex - 1);
                        }

                        continue;

                    case ConsoleKey.Home:
                        currentCompletion = null;

                        currentCursorIndex =
                            MoveCursorToIndex(
                                promptStartCol,
                                promptStartRow,
                                consoleWidth,
                                0);

                        continue;

                    case ConsoleKey.RightArrow:
                        currentCompletion = null;

                        if (currentCursorIndex < inputLine.Length)
                        {
                            currentCursorIndex =
                                MoveCursorToIndex(
                                    promptStartCol,
                                    promptStartRow,
                                    consoleWidth,
                                    currentCursorIndex + 1);
                        }

                        continue;

                    case ConsoleKey.End:
                        currentCompletion = null;

                        currentCursorIndex =
                            MoveCursorToIndex(
                                promptStartCol,
                                promptStartRow,
                                consoleWidth,
                                inputLine.Length);

                        continue;

                    case ConsoleKey.UpArrow:
                        currentCompletion = null;

                        // TODO: Ctrl+Up should allow navigation in multi-line input
                        if (currentHistory is null)
                        {
                            historyIndex = -1;

                            PSCommand command = new PSCommand()
                                                .AddCommand("Get-History");

                            currentHistory = _psesHost.InvokePSCommand <PSObject>(command, executionOptions: null, cancellationToken);

                            if (currentHistory is not null)
                            {
                                historyIndex = currentHistory.Count;
                            }
                        }

                        if (currentHistory?.Count > 0 && historyIndex > 0)
                        {
                            historyIndex--;

                            currentCursorIndex =
                                InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    (string)currentHistory[historyIndex].Properties["CommandLine"].Value,
                                    currentCursorIndex,
                                    insertIndex: 0,
                                    replaceLength: inputLine.Length);
                        }

                        continue;

                    case ConsoleKey.DownArrow:
                        currentCompletion = null;

                        // The down arrow shouldn't cause history to be loaded,
                        // it's only for navigating an active history array
                        if (historyIndex > -1 && historyIndex < currentHistory.Count &&
                            currentHistory?.Count > 0)
                        {
                            historyIndex++;

                            if (historyIndex < currentHistory.Count)
                            {
                                currentCursorIndex =
                                    InsertInput(
                                        inputLine,
                                        promptStartCol,
                                        promptStartRow,
                                        (string)currentHistory[historyIndex].Properties["CommandLine"].Value,
                                        currentCursorIndex,
                                        insertIndex: 0,
                                        replaceLength: inputLine.Length);
                            }
                            else if (historyIndex == currentHistory.Count)
                            {
                                currentCursorIndex =
                                    InsertInput(
                                        inputLine,
                                        promptStartCol,
                                        promptStartRow,
                                        string.Empty,
                                        currentCursorIndex,
                                        insertIndex: 0,
                                        replaceLength: inputLine.Length);
                            }
                        }

                        continue;

                    case ConsoleKey.Escape:
                        currentCompletion = null;
                        historyIndex      = currentHistory != null ? currentHistory.Count : -1;

                        currentCursorIndex =
                            InsertInput(
                                inputLine,
                                promptStartCol,
                                promptStartRow,
                                string.Empty,
                                currentCursorIndex,
                                insertIndex: 0,
                                replaceLength: inputLine.Length);

                        continue;

                    case ConsoleKey.Backspace:
                        currentCompletion = null;

                        if (currentCursorIndex > 0)
                        {
                            currentCursorIndex =
                                InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    string.Empty,
                                    currentCursorIndex,
                                    insertIndex: currentCursorIndex - 1,
                                    replaceLength: 1,
                                    finalCursorIndex: currentCursorIndex - 1);
                        }

                        continue;

                    case ConsoleKey.Delete:
                        currentCompletion = null;

                        if (currentCursorIndex < inputLine.Length)
                        {
                            currentCursorIndex =
                                InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    string.Empty,
                                    currentCursorIndex,
                                    replaceLength: 1,
                                    finalCursorIndex: currentCursorIndex);
                        }

                        continue;

                    case ConsoleKey.Enter:
                        string completedInput = inputLine.ToString();
                        currentCompletion = null;
                        currentHistory    = null;

                        // TODO: Add line continuation support:
                        // - When shift+enter is pressed, or
                        // - When the parse indicates incomplete input

                        //if ((keyInfo.Modifiers & ConsoleModifiers.Shift) == ConsoleModifiers.Shift)
                        //{
                        //    // TODO: Start a new line!
                        //    continue;
                        //}
                        //Parser.ParseInput(
                        //    completedInput,
                        //    out Token[] tokens,
                        //    out ParseError[] parseErrors);
                        //if (parseErrors.Any(e => e.IncompleteInput))
                        //{
                        //    // TODO: Start a new line!
                        //    continue;
                        //}

                        return(completedInput);

                    default:
                        if (keyInfo.IsCtrlC())
                        {
                            throw new PipelineStoppedException();
                        }

                        // Normal character input
                        if (keyInfo.KeyChar != 0 && !char.IsControl(keyInfo.KeyChar))
                        {
                            currentCompletion = null;

                            currentCursorIndex =
                                InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    keyInfo.KeyChar.ToString(),     // TODO: Determine whether this should take culture into account
                                    currentCursorIndex,
                                    finalCursorIndex: currentCursorIndex + 1);
                        }

                        continue;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // We've broken out of the loop
            }
            finally
            {
                Console.TreatControlCAsInput = false;
            }

            // If we break out of the loop without returning (because of the Enter key)
            // then the readline has been aborted in some way and we should return nothing
            return(null);
        }
 protected PowerShellResults <O> Invoke <O>(PSCommand psCommand)
 {
     return(this.CoreInvoke <O>(psCommand, null, null, null));
 }
        private bool IsSkypeAccountAlreadyExist(string pUserCommonName, Runspace pRunspace, PowerShell pPowerShell, PSCommand pPSCommand)
        {
            pPSCommand.AddCommand("Get-CsUser");
            pPSCommand.AddParameter("Identity", pUserCommonName);

            pPowerShell.Commands = pPSCommand;

            try
            {
                pRunspace.Open();
                pPowerShell.Runspace = pRunspace;
                Collection <PSObject> user = pPowerShell.Invoke();

                if (user == null || user.Count == 0)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            finally
            {
                pRunspace.Dispose();
                pRunspace = null;
            }
        }
Example #6
0
        /// <summary>
        /// Sets the specified variable by container variableReferenceId and variable name to the
        /// specified new value.  If the variable cannot be set or converted to that value this
        /// method will throw InvalidPowerShellExpressionException, ArgumentTransformationMetadataException, or
        /// SessionStateUnauthorizedAccessException.
        /// </summary>
        /// <param name="variableContainerReferenceId">The container (Autos, Local, Script, Global) that holds the variable.</param>
        /// <param name="name">The name of the variable prefixed with $.</param>
        /// <param name="value">The new string value.  This value must not be null.  If you want to set the variable to $null
        /// pass in the string "$null".</param>
        /// <returns>The string representation of the value the variable was set to.</returns>
        public async Task <string> SetVariableAsync(int variableContainerReferenceId, string name, string value)
        {
            Validate.IsNotNull(nameof(name), name);
            Validate.IsNotNull(nameof(value), value);

            this.logger.LogTrace($"SetVariableRequest for '{name}' to value string (pre-quote processing): '{value}'");

            // An empty or whitespace only value is not a valid expression for SetVariable.
            if (value.Trim().Length == 0)
            {
                throw new InvalidPowerShellExpressionException("Expected an expression.");
            }

            // Evaluate the expression to get back a PowerShell object from the expression string.
            PSCommand psCommand = new PSCommand();

            psCommand.AddScript(value);
            var errorMessages = new StringBuilder();
            var results       =
                await this.powerShellContext.ExecuteCommandAsync <object>(
                    psCommand,
                    errorMessages,
                    false,
                    false).ConfigureAwait(false);

            // Check if PowerShell's evaluation of the expression resulted in an error.
            object psobject = results.FirstOrDefault();

            if ((psobject == null) && (errorMessages.Length > 0))
            {
                throw new InvalidPowerShellExpressionException(errorMessages.ToString());
            }

            // If PowerShellContext.ExecuteCommand returns an ErrorRecord as output, the expression failed evaluation.
            // Ideally we would have a separate means from communicating error records apart from normal output.
            if (psobject is ErrorRecord errorRecord)
            {
                throw new InvalidPowerShellExpressionException(errorRecord.ToString());
            }

            // OK, now we have a PS object from the supplied value string (expression) to assign to a variable.
            // Get the variable referenced by variableContainerReferenceId and variable name.
            VariableContainerDetails variableContainer = null;

            await this.debugInfoHandle.WaitAsync().ConfigureAwait(false);

            try
            {
                variableContainer = (VariableContainerDetails)this.variables[variableContainerReferenceId];
            }
            finally
            {
                this.debugInfoHandle.Release();
            }

            VariableDetailsBase variable = variableContainer.Children[name];
            // Determine scope in which the variable lives. This is required later for the call to Get-Variable -Scope.
            string scope = null;

            if (variableContainerReferenceId == this.scriptScopeVariables.Id)
            {
                scope = "Script";
            }
            else if (variableContainerReferenceId == this.globalScopeVariables.Id)
            {
                scope = "Global";
            }
            else
            {
                // Determine which stackframe's local scope the variable is in.
                StackFrameDetails[] stackFrames = await this.GetStackFramesAsync().ConfigureAwait(false);

                for (int i = 0; i < stackFrames.Length; i++)
                {
                    var stackFrame = stackFrames[i];
                    if (stackFrame.LocalVariables.ContainsVariable(variable.Id))
                    {
                        scope = i.ToString();
                        break;
                    }
                }
            }

            if (scope == null)
            {
                // Hmm, this would be unexpected.  No scope means do not pass GO, do not collect $200.
                throw new Exception("Could not find the scope for this variable.");
            }

            // Now that we have the scope, get the associated PSVariable object for the variable to be set.
            psCommand.Commands.Clear();
            psCommand = new PSCommand();
            psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-Variable");
            psCommand.AddParameter("Name", name.TrimStart('$'));
            psCommand.AddParameter("Scope", scope);

            IEnumerable <PSVariable> result = await this.powerShellContext.ExecuteCommandAsync <PSVariable>(psCommand, sendErrorToHost : false).ConfigureAwait(false);

            PSVariable psVariable = result.FirstOrDefault();

            if (psVariable == null)
            {
                throw new Exception($"Failed to retrieve PSVariable object for '{name}' from scope '{scope}'.");
            }

            // We have the PSVariable object for the variable the user wants to set and an object to assign to that variable.
            // The last step is to determine whether the PSVariable is "strongly typed" which may require a conversion.
            // If it is not strongly typed, we simply assign the object directly to the PSVariable potentially changing its type.
            // Turns out ArgumentTypeConverterAttribute is not public. So we call the attribute through it's base class -
            // ArgumentTransformationAttribute.
            var argTypeConverterAttr =
                psVariable.Attributes
                .OfType <ArgumentTransformationAttribute>()
                .FirstOrDefault(a => a.GetType().Name.Equals("ArgumentTypeConverterAttribute"));

            if (argTypeConverterAttr != null)
            {
                // PSVariable is strongly typed. Need to apply the conversion/transform to the new value.
                psCommand.Commands.Clear();
                psCommand = new PSCommand();
                psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-Variable");
                psCommand.AddParameter("Name", "ExecutionContext");
                psCommand.AddParameter("ValueOnly");

                errorMessages.Clear();

                var getExecContextResults =
                    await this.powerShellContext.ExecuteCommandAsync <object>(
                        psCommand,
                        errorMessages,
                        sendErrorToHost : false).ConfigureAwait(false);

                EngineIntrinsics executionContext = getExecContextResults.OfType <EngineIntrinsics>().FirstOrDefault();

                var msg = $"Setting variable '{name}' using conversion to value: {psobject ?? "<null>"}";
                this.logger.LogTrace(msg);

                psVariable.Value = argTypeConverterAttr.Transform(executionContext, psobject);
            }
            else
            {
                // PSVariable is *not* strongly typed. In this case, whack the old value with the new value.
                var msg = $"Setting variable '{name}' directly to value: {psobject ?? "<null>"} - previous type was {psVariable.Value?.GetType().Name ?? "<unknown>"}";
                this.logger.LogTrace(msg);
                psVariable.Value = psobject;
            }

            // Use the VariableDetails.ValueString functionality to get the string representation for client debugger.
            // This makes the returned string consistent with the strings normally displayed for variables in the debugger.
            var tempVariable = new VariableDetails(psVariable);

            this.logger.LogTrace($"Set variable '{name}' to: {tempVariable.ValueString ?? "<null>"}");
            return(tempVariable.ValueString);
        }
Example #7
0
        public MSActorReturnMessageModel RemoveDirectory(string computername, string path)
        {
            try
            {
                MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");

                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("Remove-Item");
                        command.AddParameter("Path", path);
                        command.AddParameter("Recurse");
                        command.AddParameter("Force");
                        powershell.Commands = command;
                        powershell.Invoke();

                        if (powershell.Streams.Error.Count > 0)
                        {
                            RemoteException ex = powershell.Streams.Error[0].Exception as RemoteException;
                            if (ex.SerializedRemoteException.TypeNames.Contains("Deserialized.System.Management.Automation.ItemNotFoundException"))
                            {
                                return(successMessage);
                            }
                            else if (ex.SerializedRemoteException.TypeNames.Contains("Deserialized.System.IO.PathTooLongException"))
                            {
                                // Run our script for extra long paths instead
                                using (PowerShell powershell1 = PowerShell.Create())
                                {
                                    powershell1.Runspace = runspace;

                                    PSCommand command1 = new PSCommand();
                                    command1.AddCommand("Set-ExecutionPolicy");
                                    command1.AddParameter("ExecutionPolicy", "RemoteSigned");
                                    command1.AddParameter("Scope", "Process");
                                    command1.AddParameter("Force");
                                    powershell1.Commands = command1;
                                    powershell1.Invoke();
                                    if (powershell1.Streams.Error.Count > 0)
                                    {
                                        throw powershell1.Streams.Error[0].Exception;
                                    }
                                    powershell1.Streams.ClearStreams();

                                    command1 = new PSCommand();
                                    command1.AddScript(". D:\\PathTooLong.ps1");
                                    powershell1.Commands = command1;
                                    powershell1.Invoke();
                                    if (powershell1.Streams.Error.Count > 0)
                                    {
                                        throw powershell1.Streams.Error[0].Exception;
                                    }
                                    powershell1.Streams.ClearStreams();

                                    command1 = new PSCommand();
                                    command1.AddCommand("Remove-PathToLongDirectory");
                                    command1.AddArgument(path);
                                    powershell1.Commands = command1;
                                    powershell1.Invoke();
                                    if (powershell1.Streams.Error.Count > 0)
                                    {
                                        throw powershell1.Streams.Error[0].Exception;
                                    }
                                    powershell1.Streams.ClearStreams();
                                }
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Example #8
0
        public PowerShellResults <MobileDeviceRow> UnBlockOrCancelWipeDevice(Identity[] identities, BaseWebServiceParameters parameters)
        {
            PSCommand psCommand = new PSCommand().AddCommand("Clear-MobileDevice").AddParameter("Cancel", new SwitchParameter(true));

            return(base.InvokeAndGetObject <MobileDeviceRow>(psCommand, identities, parameters));
        }
Example #9
0
        public MSActorReturnMessageModel AddNetShare(string name, string computername, string path)
        {
            MSActorReturnMessageModel successMessage;

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        string    script  = String.Format("net share {0}={1} \"/GRANT:Everyone,Full\"", name, path);
                        command.AddScript(script);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError")
                            {
                                // If the share already exists it might be okay (see "else" below). Otherwise this is an error.
                                if (powershell.Streams.Error[0].Exception.Message != "The name has already been shared.")
                                {
                                    StringBuilder msgBuilder = new StringBuilder();
                                    foreach (ErrorRecord errorRec in powershell.Streams.Error)
                                    {
                                        // Kludge to fix a weird bug with blank lines in the error output
                                        if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message)
                                        {
                                            msgBuilder.AppendLine();
                                        }
                                        else
                                        {
                                            msgBuilder.AppendLine(errorRec.Exception.Message);
                                        }
                                    }
                                    throw new Exception(msgBuilder.ToString());
                                }
                                else
                                {
                                    powershell.Streams.ClearStreams();

                                    // Check that the existing share has the same path
                                    command = new PSCommand();
                                    script  = String.Format("net share {0}", name);
                                    command.AddScript(script);
                                    powershell.Commands = command;
                                    Collection <PSObject> ret = powershell.Invoke();
                                    if (powershell.Streams.Error.Count > 0)
                                    {
                                        throw powershell.Streams.Error[0].Exception;
                                    }
                                    powershell.Streams.ClearStreams();

                                    // Find the first (hopefully only) line in the output with "Path" at the beginning
                                    string pathResultLine = ret.First(x => (x.BaseObject as string).StartsWith("Path")).BaseObject as string;
                                    if (pathResultLine == null)
                                    {
                                        // There was not a line in the output containing the path, so we assume we got an error message instead.
                                        string message = ret.First(x => (x.BaseObject as string).Length > 0).BaseObject as string;
                                        throw new Exception(message);
                                    }
                                    else
                                    {
                                        // The output looks like "Path              D:\Users\srenker".
                                        // The regular expression below separates this into groups.
                                        // Meaning of the next regex (from left to right):
                                        // 1. Save all the characters that are not blanks into a group. (\S+)
                                        // 2. Skip over all characters that are blanks. \s+
                                        // 3. Save all the other characters into a group, up to end of line. (.+)$
                                        // It's done this way because the path may have a space embedded in the name.
                                        // The @ before the string tells C# not to escape any characters before passing it
                                        // to the regular expression processor.
                                        GroupCollection groups = Regex.Match(pathResultLine, @"(\S+)\s+(.+)$").Groups;
                                        // Group 2 (#3 above) is the path value.
                                        string pathResult = groups[2].Value;
                                        if (pathResult == path)
                                        {
                                            successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                                            return(successMessage);
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format("Share '{0}' already exists for a different path '{1}'.", name, pathResult));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                            // powershell.Streams.ClearStreams();  -- is unreachable here
                        }

                        successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Example #10
0
        private MSActorReturnMessageModel AddFolderAccess(string identity, string computername, string path, string accesstype)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        // Note: The commands stacked on top of each other (prior to invoking) below have the effect
                        // of piping the output of one into the other, e.g. the result of Get-Acl becomes an input to Set-Variable.
                        // We need to work this way on a remote session so that type information does not get changed by
                        // retrieving the objects back to the local session.

                        PSCommand command = new PSCommand();
                        command.AddCommand("Get-Acl");
                        command.AddParameter("Path", path);
                        command.AddCommand("Set-Variable");
                        command.AddParameter("Name", "acl");
                        powershell.Commands = command;
                        Collection <PSObject> result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        command = new PSCommand();
                        command.AddCommand("New-Object");
                        command.AddParameter("TypeName", "System.Security.AccessControl.FileSystemAccessRule");
                        command.AddParameter("ArgumentList",
                                             new object[]
                        {
                            identity,
                            accesstype,
                            "ContainerInherit,ObjectInherit",
                            "None",
                            "Allow"
                        });
                        command.AddCommand("Set-Variable");
                        command.AddParameter("Name", "perms");
                        powershell.Commands = command;
                        result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        command = new PSCommand();
                        command.AddScript("$acl.SetAccessRule($perms)");
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        command = new PSCommand();
                        command.AddScript(String.Format("Set-Acl -AclObject $acl -Path {0}", path));
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
 protected PowerShellResults InvokeAsync(PSCommand psCommand, Action <PowerShellResults> onCompleted)
 {
     return(AsyncServiceManager.InvokeAsync(() => this.Invoke(psCommand), onCompleted, RbacPrincipal.Current.UniqueName, AsyncTaskType.Default, psCommand.ToTraceString()));
 }
Example #12
0
        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), false))
                {
                    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 is string commandString)
                        {
                            PowerShellLog.Info($"Executing a debug command in ScriptSession '{Key}'.");
                            PowerShellLog.Debug(commandString);
                            DebuggerCommandResults results = null;
                            try
                            {
                                var psCommand     = new PSCommand();
                                var scriptCommand = new Command(commandString, true)
                                {
                                    MergeUnclaimedPreviousCommandResults = PipelineResultTypes.Warning
                                };
                                psCommand.AddCommand(scriptCommand)
                                .AddCommand(OutDefaultCommand);

                                results          = debugger?.ProcessCommand(psCommand, output);
                                ImmediateResults = output;
                                LogErrors(null, output.ToList());
                            }
                            catch (Exception ex)
                            {
                                PowerShellLog.Error("Error while executing Debugging command.", ex);
                                ImmediateCommand = null;
                                host.UI.WriteErrorLine(GetExceptionString(ex, ExceptionStringFormat.Default));
                            }

                            if (results?.ResumeAction != null)
                            {
                                resumeAction = results.ResumeAction;
                            }
                            ImmediateCommand = null;
                        }
                        else
                        {
                            Thread.Sleep(20);
                        }
                    }


                    args.ResumeAction = resumeAction ?? DebuggerResumeAction.Continue;
                }
            }
            finally
            {
                DebuggingInBreakpoint = false;
            }
        }
 protected PowerShellResults Invoke(PSCommand psCommand)
 {
     return(this.Invoke(psCommand, Identity.FromExecutingUserId(), null));
 }
 protected PowerShellResults <O> GetObject <O>(PSCommand psCommand)
 {
     EcpPerfCounters.WebServiceGetObject.Increment();
     return(psCommand.Invoke(this.runspaceMediator, null, null));
 }
        private async Task CheckPackageManagement()
        {
            PSCommand getModule = new PSCommand().AddCommand("Get-Module").AddParameter("ListAvailable").AddParameter("Name", "PackageManagement");

            foreach (PSModuleInfo module in await _powerShellContextService.ExecuteCommandAsync <PSModuleInfo>(getModule).ConfigureAwait(false))
            {
                // The user has a good enough version of PackageManagement
                if (module.Version >= s_desiredPackageManagementVersion)
                {
                    break;
                }

                _logger.LogDebug("Old version of PackageManagement detected.");

                if (_powerShellContextService.CurrentRunspace.Runspace.SessionStateProxy.LanguageMode != PSLanguageMode.FullLanguage)
                {
                    _languageServer.Window.ShowWarning("You have an older version of PackageManagement known to cause issues with the PowerShell extension. Please run the following command in a new Windows PowerShell session and then restart the PowerShell extension: `Install-Module PackageManagement -Force -AllowClobber -MinimumVersion 1.4.6`");
                    return;
                }

                var takeActionText = "Yes";
                MessageActionItem messageAction = await _languageServer.Window.ShowMessageRequest(new ShowMessageRequestParams
                {
                    Message = "You have an older version of PackageManagement known to cause issues with the PowerShell extension. Would you like to update PackageManagement (You will need to restart the PowerShell extension after)?",
                    Type    = MessageType.Warning,
                    Actions = new[]
                    {
                        new MessageActionItem
                        {
                            Title = takeActionText
                        },
                        new MessageActionItem
                        {
                            Title = "Not now"
                        }
                    }
                }).ConfigureAwait(false);

                // If the user chose "Not now" ignore it for the rest of the session.
                if (messageAction?.Title == takeActionText)
                {
                    StringBuilder errors = new StringBuilder();
                    await _powerShellContextService.ExecuteScriptStringAsync(
                        "powershell.exe -NoLogo -NoProfile -Command '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Install-Module -Name PackageManagement -Force -MinimumVersion 1.4.6 -Scope CurrentUser -AllowClobber -Repository PSGallery'",
                        errors,
                        writeInputToHost : true,
                        writeOutputToHost : true,
                        addToHistory : true).ConfigureAwait(false);

                    if (errors.Length == 0)
                    {
                        _logger.LogDebug("PackageManagement is updated.");
                        _languageServer.Window.ShowMessage(new ShowMessageParams
                        {
                            Type    = MessageType.Info,
                            Message = "PackageManagement updated, If you already had PackageManagement loaded in your session, please restart the PowerShell extension."
                        });
                    }
                    else
                    {
                        // There were errors installing PackageManagement.
                        _logger.LogError($"PackageManagement installation had errors: {errors.ToString()}");
                        _languageServer.Window.ShowMessage(new ShowMessageParams
                        {
                            Type    = MessageType.Error,
                            Message = "PackageManagement update failed. This might be due to PowerShell Gallery using TLS 1.2. More info can be found at https://aka.ms/psgallerytls"
                        });
                    }
                }
            }
        }
 public MonadPipelineProxy(RunspaceProxy proxy, IEnumerable input, PSCommand commands, WorkUnit[] workUnits) : base(proxy, workUnits, commands)
 {
     this.InitInput(input);
 }
 public MonadPipelineProxy(RunspaceProxy proxy, IEnumerable input, PSCommand commands) : this(proxy, commands)
 {
     this.InitInput(input);
 }
Example #18
0
        /// <summary>
        /// Invokes a custom ReadLine method that is similar to but more basic than PSReadLine.
        /// This method should be used when PSReadLine is disabled, either by user settings or
        /// unsupported PowerShell versions.
        /// </summary>
        /// <param name="isCommandLine">
        /// Indicates whether ReadLine should act like a command line.
        /// </param>
        /// <param name="cancellationToken">
        /// The cancellation token that will be checked prior to completing the returned task.
        /// </param>
        /// <returns>
        /// A task object representing the asynchronus operation. The Result property on
        /// the task object returns the user input string.
        /// </returns>
        internal async Task <string> InvokeLegacyReadLineAsync(bool isCommandLine, CancellationToken cancellationToken)
        {
            // TODO: Is inputBeforeCompletion used?
            string            inputBeforeCompletion = null;
            string            inputAfterCompletion  = null;
            CommandCompletion currentCompletion     = null;

            int historyIndex = -1;
            Collection <PSObject> currentHistory = null;

            StringBuilder inputLine = new StringBuilder();

            int initialCursorCol = await ConsoleProxy.GetCursorLeftAsync(cancellationToken).ConfigureAwait(false);

            int initialCursorRow = await ConsoleProxy.GetCursorTopAsync(cancellationToken).ConfigureAwait(false);

            // TODO: Are these used?
            int initialWindowLeft = Console.WindowLeft;
            int initialWindowTop  = Console.WindowTop;

            int currentCursorIndex = 0;

            Console.TreatControlCAsInput = true;

            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    ConsoleKeyInfo keyInfo = await ReadKeyAsync(cancellationToken).ConfigureAwait(false);

                    // Do final position calculation after the key has been pressed
                    // because the window could have been resized before then
                    int promptStartCol = initialCursorCol;
                    int promptStartRow = initialCursorRow;
                    int consoleWidth   = Console.WindowWidth;

                    if ((int)keyInfo.Key == 3 ||
                        keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
                    {
                        throw new PipelineStoppedException();
                    }
                    else if (keyInfo.Key == ConsoleKey.Tab && isCommandLine)
                    {
                        if (currentCompletion == null)
                        {
                            inputBeforeCompletion = inputLine.ToString();
                            inputAfterCompletion  = null;

                            // TODO: This logic should be moved to AstOperations or similar!

                            if (this.powerShellContext.IsDebuggerStopped)
                            {
                                PSCommand command = new PSCommand();
                                command.AddCommand("TabExpansion2");
                                command.AddParameter("InputScript", inputBeforeCompletion);
                                command.AddParameter("CursorColumn", currentCursorIndex);
                                command.AddParameter("Options", null);

                                var results = await this.powerShellContext
                                              .ExecuteCommandAsync <CommandCompletion>(command, sendOutputToHost : false, sendErrorToHost : false)
                                              .ConfigureAwait(false);

                                currentCompletion = results.FirstOrDefault();
                            }
                            else
                            {
                                using (RunspaceHandle runspaceHandle = await this.powerShellContext.GetRunspaceHandleAsync().ConfigureAwait(false))
                                    using (PowerShell powerShell = PowerShell.Create())
                                    {
                                        powerShell.Runspace = runspaceHandle.Runspace;
                                        currentCompletion   =
                                            CommandCompletion.CompleteInput(
                                                inputBeforeCompletion,
                                                currentCursorIndex,
                                                null,
                                                powerShell);

                                        if (currentCompletion.CompletionMatches.Count > 0)
                                        {
                                            int replacementEndIndex =
                                                currentCompletion.ReplacementIndex +
                                                currentCompletion.ReplacementLength;

                                            inputAfterCompletion =
                                                inputLine.ToString(
                                                    replacementEndIndex,
                                                    inputLine.Length - replacementEndIndex);
                                        }
                                        else
                                        {
                                            currentCompletion = null;
                                        }
                                    }
                            }
                        }

                        CompletionResult completion =
                            currentCompletion?.GetNextResult(
                                !keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift));

                        if (completion != null)
                        {
                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    $"{completion.CompletionText}{inputAfterCompletion}",
                                    currentCursorIndex,
                                    insertIndex: currentCompletion.ReplacementIndex,
                                    replaceLength: inputLine.Length - currentCompletion.ReplacementIndex,
                                    finalCursorIndex: currentCompletion.ReplacementIndex + completion.CompletionText.Length);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.LeftArrow)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex > 0)
                        {
                            currentCursorIndex =
                                this.MoveCursorToIndex(
                                    promptStartCol,
                                    promptStartRow,
                                    consoleWidth,
                                    currentCursorIndex - 1);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Home)
                    {
                        currentCompletion = null;

                        currentCursorIndex =
                            this.MoveCursorToIndex(
                                promptStartCol,
                                promptStartRow,
                                consoleWidth,
                                0);
                    }
                    else if (keyInfo.Key == ConsoleKey.RightArrow)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex < inputLine.Length)
                        {
                            currentCursorIndex =
                                this.MoveCursorToIndex(
                                    promptStartCol,
                                    promptStartRow,
                                    consoleWidth,
                                    currentCursorIndex + 1);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.End)
                    {
                        currentCompletion = null;

                        currentCursorIndex =
                            this.MoveCursorToIndex(
                                promptStartCol,
                                promptStartRow,
                                consoleWidth,
                                inputLine.Length);
                    }
                    else if (keyInfo.Key == ConsoleKey.UpArrow && isCommandLine)
                    {
                        currentCompletion = null;

                        // TODO: Ctrl+Up should allow navigation in multi-line input

                        if (currentHistory == null)
                        {
                            historyIndex = -1;

                            PSCommand command = new PSCommand();
                            command.AddCommand("Get-History");

                            currentHistory = await this.powerShellContext.ExecuteCommandAsync <PSObject>(command, sendOutputToHost : false, sendErrorToHost : false)
                                             .ConfigureAwait(false)
                                             as Collection <PSObject>;

                            if (currentHistory != null)
                            {
                                historyIndex = currentHistory.Count;
                            }
                        }

                        if (currentHistory != null && currentHistory.Count > 0 && historyIndex > 0)
                        {
                            historyIndex--;

                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    (string)currentHistory[historyIndex].Properties["CommandLine"].Value,
                                    currentCursorIndex,
                                    insertIndex: 0,
                                    replaceLength: inputLine.Length);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.DownArrow && isCommandLine)
                    {
                        currentCompletion = null;

                        // The down arrow shouldn't cause history to be loaded,
                        // it's only for navigating an active history array

                        if (historyIndex > -1 && historyIndex < currentHistory.Count &&
                            currentHistory != null && currentHistory.Count > 0)
                        {
                            historyIndex++;

                            if (historyIndex < currentHistory.Count)
                            {
                                currentCursorIndex =
                                    this.InsertInput(
                                        inputLine,
                                        promptStartCol,
                                        promptStartRow,
                                        (string)currentHistory[historyIndex].Properties["CommandLine"].Value,
                                        currentCursorIndex,
                                        insertIndex: 0,
                                        replaceLength: inputLine.Length);
                            }
                            else if (historyIndex == currentHistory.Count)
                            {
                                currentCursorIndex =
                                    this.InsertInput(
                                        inputLine,
                                        promptStartCol,
                                        promptStartRow,
                                        string.Empty,
                                        currentCursorIndex,
                                        insertIndex: 0,
                                        replaceLength: inputLine.Length);
                            }
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Escape)
                    {
                        currentCompletion = null;
                        historyIndex      = currentHistory != null ? currentHistory.Count : -1;

                        currentCursorIndex =
                            this.InsertInput(
                                inputLine,
                                promptStartCol,
                                promptStartRow,
                                string.Empty,
                                currentCursorIndex,
                                insertIndex: 0,
                                replaceLength: inputLine.Length);
                    }
                    else if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex > 0)
                        {
                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    string.Empty,
                                    currentCursorIndex,
                                    insertIndex: currentCursorIndex - 1,
                                    replaceLength: 1,
                                    finalCursorIndex: currentCursorIndex - 1);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Delete)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex < inputLine.Length)
                        {
                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    string.Empty,
                                    currentCursorIndex,
                                    replaceLength: 1,
                                    finalCursorIndex: currentCursorIndex);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Enter)
                    {
                        string completedInput = inputLine.ToString();
                        currentCompletion = null;
                        currentHistory    = null;

                        //if ((keyInfo.Modifiers & ConsoleModifiers.Shift) == ConsoleModifiers.Shift)
                        //{
                        //    // TODO: Start a new line!
                        //    continue;
                        //}

                        Parser.ParseInput(
                            completedInput,
                            out Token[] tokens,
                            out ParseError[] parseErrors);
 protected PowerShellResults RemoveObjects(PSCommand psCommand, Identity[] identities, WebServiceParameters parameters)
 {
     EcpPerfCounters.WebServiceRemoveObject.Increment();
     return(this.Invoke(psCommand, identities, parameters));
 }
Example #20
0
        public MSActorReturnMessageModel RemoveNetShare(string name, string computername, string path)
        {
            MSActorReturnMessageModel successMessage;

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        // First check that the share name is for the correct path
                        PSCommand command = new PSCommand();
                        string    script  = String.Format("net share {0}", name);
                        command.AddScript(script);
                        powershell.Commands = command;
                        Collection <PSObject> ret = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError")
                            {
                                // If the share does not exist return success
                                if (powershell.Streams.Error[0].Exception.Message == "This shared resource does not exist.")
                                {
                                    successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                                    return(successMessage);
                                }
                                else
                                {
                                    StringBuilder msgBuilder = new StringBuilder();
                                    foreach (ErrorRecord errorRec in powershell.Streams.Error)
                                    {
                                        // Kludge to fix a weird bug with blank lines in the error output
                                        if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message)
                                        {
                                            msgBuilder.AppendLine();
                                        }
                                        else
                                        {
                                            msgBuilder.AppendLine(errorRec.Exception.Message);
                                        }
                                    }
                                    throw new Exception(msgBuilder.ToString());
                                }
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        // Find the first (hopefully only) line in the output with "Path" at the beginning
                        string pathResultLine = ret.First(x => (x.BaseObject as string).StartsWith("Path")).BaseObject as string;
                        // The output looks like "Path              D:\Users\srenker".
                        // The regular expression below separates this into groups.
                        // Meaning of the next regex (from left to right):
                        // 1. Save all the characters that are not blanks into a group. (\S+)
                        // 2. Skip over all characters that are blanks. \s+
                        // 3. Save all the other characters into a group, up to end of line. (.+)$
                        // It's done this way because the path may have a space embedded in the name.
                        // The @ before the string tells C# not to escape any characters before passing it
                        // to the regular expression processor.
                        GroupCollection groups = Regex.Match(pathResultLine, @"(\S+)\s+(.+)$").Groups;
                        // Group 2 (#3 above) is the path value.
                        string existingPath = groups[2].Value;
                        if (!String.Equals(path, existingPath, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new Exception(String.Format("Share '{0}' is for path '{1}', different than specified.", name, existingPath));
                        }

                        // Now delete the share
                        script = String.Format("net share {0} /delete", name);
                        command.AddScript(script);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError")
                            {
                                StringBuilder msgBuilder = new StringBuilder();
                                foreach (ErrorRecord errorRec in powershell.Streams.Error)
                                {
                                    // Kludge to fix a weird bug with blank lines in the error output
                                    if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message)
                                    {
                                        msgBuilder.AppendLine();
                                    }
                                    else
                                    {
                                        msgBuilder.AppendLine(errorRec.Exception.Message);
                                    }
                                }
                                throw new Exception(msgBuilder.ToString());
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
 private PowerShellResults CoreInvoke(PSCommand psCommand, IEnumerable pipelineInput, Identity translationIdentity, WebServiceParameters parameters)
 {
     return(new PowerShellResults(this.CoreInvoke <PSObject>(psCommand, pipelineInput, translationIdentity, parameters)));
 }
Example #22
0
        public MSActorReturnMessageModel AddDirQuota(string computername, string path, string limit)
        {
            // Project P0975: Replace old command line scripts with new PowerShell commands,
            // required after upgrading the Windows Server version on the file servers
            MSActorReturnMessageModel successMessage;

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("New-FsrmQuota");
                        command.AddParameter("Path", path);
                        command.AddParameter("Size", NumericLimit(limit));
                        powershell.Commands = command;
                        Collection <PSObject> result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].Exception.Message.Trim() != "0x80045303, The specified object already exists.")
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                            else
                            {
                                powershell.Streams.ClearStreams();

                                // Check that the existing quota has the same limit
                                command = new PSCommand();
                                command.AddCommand("Get-FsrmQuota");
                                command.AddParameter("Path", path);
                                powershell.Commands = command;
                                Collection <PSObject> res = powershell.Invoke();
                                if (powershell.Streams.Error.Count > 0)
                                {
                                    throw powershell.Streams.Error[0].Exception;
                                }
                                CimInstance quota = (CimInstance)res.FirstOrDefault()?.BaseObject;
                                if ((ulong)quota.CimInstanceProperties["Size"].Value != NumericLimit(limit))
                                {
                                    throw new Exception("A different quota already exists on that folder");
                                }
                            }
                        }
                        powershell.Streams.ClearStreams();

                        successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
        protected PowerShellResults <L> GetList <L, F>(string getCmdlet, F filter, SortOptions sort) where F : WebServiceParameters, new()
        {
            PSCommand psCommand = new PSCommand().AddCommand(getCmdlet);

            return(this.GetList <L, F>(psCommand, filter, sort));
        }
Example #24
0
        static void Main(string[] args)
        {
            #region vars

            bool     useRunspace          = false;
            bool     useRunspace2         = true;
            bool     usePipeline          = false;
            Runspace rs                   = null;
            string   kerberosUri          = "http://CHAADSYNC.CORR.ROUND-ROCK.TX.US/PowerShell";
            string   chaadUri             = "http://CHAADSYNC.CORR.ROUND-ROCK.TX.US";
            string   schemaUri            = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
            string   schemaUriCHAAD       = "http://schemas.microsoft.com/powershell";
            string   server               = "CHAADSYNC.CORR.ROUND-ROCK.TX.US";
            Collection <PSObject> results = null;

            #endregion vars

            #region setupcreds

            Console.Write("Enter password: "******"corr\jmcarthur", secPass);

            //WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
            //    new Uri(kerberosUri),
            //    schemaUriCHAAD, credentials);
            //connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;

            #endregion setupcreds

            #region runspace

            if (useRunspace)
            {
                rs = RunspaceFactory.CreateRunspace();
                rs.Open();
                PowerShell ps      = PowerShell.Create();
                PSCommand  command = new PSCommand();
                command.AddCommand("New-PSSession");
                command.AddParameter("ConfigurationName", "Microsoft.Exchange");
                command.AddParameter("ConnectionUri", kerberosUri);
                command.AddParameter("Credential", credentials);
                command.AddParameter("Authentication", "kerberos");
                ps.Commands = command;
                ps.Runspace = rs;
                Collection <PSSession> result = ps.Invoke <PSSession>();

                ps      = PowerShell.Create();
                command = new PSCommand();
                command.AddCommand("Set-Variable");
                command.AddParameter("Name", "ra");
                command.AddParameter("Value", result[0]);
                ps.Commands = command;
                ps.Runspace = rs;
                ps.Invoke();

                ps      = PowerShell.Create();
                command = new PSCommand();
                command.AddScript("Import-PSSession -Session $ra");
                ps.Commands = command;
                ps.Runspace = rs;
                ps.Invoke();

                ps      = PowerShell.Create();
                command = new PSCommand();
                command.AddScript("Get-Recipient");
                command.AddParameter("ResultSize", "10");
                ps.Commands = command;
                ps.Runspace = rs;
                results     = ps.Invoke();
            }
            else if (useRunspace2)
            {
                rs = RunspaceFactory.CreateRunspace();
                rs.Open();
                PowerShell ps      = PowerShell.Create();
                PSCommand  command = new PSCommand();
                command.AddCommand("New-PSSession");
                command.AddParameter("ComputerName", server);
                command.AddParameter("Credential", credentials);
                command.AddParameter("Authentication", "Kerberos");
                ps.Commands = command;
                ps.Runspace = rs;
                Collection <PSSession> result = ps.Invoke <PSSession>();

                ps      = PowerShell.Create();
                command = new PSCommand();
                command.AddCommand("Set-Variable");
                command.AddParameter("Name", "ra");
                command.AddParameter("Value", result[0]);
                ps.Commands = command;
                ps.Runspace = rs;
                ps.Invoke();

                ps      = PowerShell.Create();
                command = new PSCommand();
                command.AddScript("Import-PSSession -Session $ra");
                ps.Commands = command;
                ps.Runspace = rs;
                ps.Invoke();

                ps      = PowerShell.Create();
                command = new PSCommand();
                command.AddScript("Import-Module -Session $ra");
                //command.AddCommand("Import-Module");
                command.AddArgument(@"C:\Program Files\Microsoft Azure AD Sync\Bin\ADSync\ADSync.psd1");
                ps.Commands = command;
                ps.Runspace = rs;
                //results = ps.Invoke();

                ps      = PowerShell.Create();
                command = new PSCommand();
                command.AddScript(@"Invoke-Command -Session $ra -ScriptBlock {Start-ADSyncSyncCycle -PolicyType Delta}");
                ps.Commands = command;
                ps.Runspace = rs;
                try
                {
                    results = ps.Invoke();
                }
                catch (Exception e)
                {
                    Console.WriteLine(String.Format("Caught exception running sync: {0}", e.Message));
                }
            }
            //else if (usePipeline)
            //{
            //    rs = RunspaceFactory.CreateRunspace(connectionInfo);
            //    rs.Open();
            //    Pipeline pipe = rs.CreatePipeline();
            //    pipe.Commands.Add("Import-Module");
            //    var command = pipe.Commands[0];
            //    command.Parameters.Add("Name", @"C:\Program Files\Microsoft Azure AD Sync\Bin\ADSync\ADSync.psd1");
            //    results = pipe.Invoke();
            //}

            #endregion runspace

            #region wrapup

            foreach (Object res in results)
            {
                Console.WriteLine(res);
            }
            Console.WriteLine("That's all, folks");
            Console.ReadKey();

            #endregion wrapup
        }
 protected PowerShellResults <L> GetObjectForList <L>(PSCommand psCommand, Identity identity)
 {
     return(this.GetObject <L>(psCommand, identity));
 }
Example #26
0
        /// <summary>
        /// Gets the PowerShell version details for the given runspace.
        /// </summary>
        /// <param name="logger">An ILogger implementation used for writing log messages.</param>
        /// <param name="pwsh">The PowerShell instance for which to to get the version.</param>
        /// <returns>A new PowerShellVersionDetails instance.</returns>
        public static PowerShellVersionDetails GetVersionDetails(ILogger logger, PowerShell pwsh)
        {
            Version powerShellVersion = new(5, 0);
            string versionString = null;
            string powerShellEdition = "Desktop";
            PowerShellProcessArchitecture architecture = PowerShellProcessArchitecture.Unknown;

            try
            {
                Hashtable psVersionTable = pwsh
                    .AddScript("$PSVersionTable", useLocalScope: true)
                    .InvokeAndClear<Hashtable>()
                    .FirstOrDefault();

                if (psVersionTable != null)
                {
                    if (psVersionTable["PSEdition"] is string edition)
                    {
                        powerShellEdition = edition;
                    }

                    // The PSVersion value will either be of Version or SemanticVersion.
                    // In the former case, take the value directly.  In the latter case,
                    // generate a Version from its string representation.
                    object version = psVersionTable["PSVersion"];
                    if (version is Version version2)
                    {
                        powerShellVersion = version2;
                    }
                    else if (version != null)
                    {
                        // Expected version string format is 6.0.0-alpha so build a simpler version from that
                        powerShellVersion = new Version(version.ToString().Split('-')[0]);
                    }

                    versionString = psVersionTable["GitCommitId"] is string gitCommitId ? gitCommitId : powerShellVersion.ToString();

                    PSCommand procArchCommand = new PSCommand().AddScript("$env:PROCESSOR_ARCHITECTURE", useLocalScope: true);

                    string arch = pwsh
                        .AddScript("$env:PROCESSOR_ARCHITECTURE", useLocalScope: true)
                        .InvokeAndClear<string>()
                        .FirstOrDefault();

                    if (arch != null)
                    {
                        if (string.Equals(arch, "AMD64", StringComparison.CurrentCultureIgnoreCase))
                        {
                            architecture = PowerShellProcessArchitecture.X64;
                        }
                        else if (string.Equals(arch, "x86", StringComparison.CurrentCultureIgnoreCase))
                        {
                            architecture = PowerShellProcessArchitecture.X86;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogWarning(
                    "Failed to look up PowerShell version, defaulting to version 5.\r\n\r\n" + ex.ToString());
            }

            return new PowerShellVersionDetails(
                powerShellVersion,
                versionString,
                powerShellEdition,
                architecture);
        }
Example #27
0
 public static void SetPowerShellInstance(PowerShell instance)
 {
     PowerShellAgent.PowerShellInstance = instance;
     PowerShellAgent.InitCommand        = instance.Commands;
 }
        /// <summary>
        /// Checks if Plaster is installed on the user's machine.
        /// </summary>
        /// <returns>A Task that can be awaited until the check is complete.  The result will be true if Plaster is installed.</returns>
        public async Task <bool> ImportPlasterIfInstalledAsync()
        {
            if (!this.isPlasterInstalled.HasValue)
            {
                PSCommand psCommand = new PSCommand();

                psCommand
                .AddCommand("Get-Module")
                .AddParameter("ListAvailable")
                .AddParameter("Name", "Plaster");

                psCommand
                .AddCommand("Sort-Object")
                .AddParameter("Descending")
                .AddParameter("Property", "Version");

                psCommand
                .AddCommand("Select-Object")
                .AddParameter("First", 1);

                this.logger.Write(LogLevel.Verbose, "Checking if Plaster is installed...");

                var getResult =
                    await this.powerShellContext.ExecuteCommandAsync <PSObject>(
                        psCommand, false, false);

                PSObject moduleObject = getResult.First();
                this.isPlasterInstalled = moduleObject != null;
                string installedQualifier =
                    this.isPlasterInstalled.Value
                        ? string.Empty : "not ";

                this.logger.Write(
                    LogLevel.Verbose,
                    $"Plaster is {installedQualifier}installed!");

                // Attempt to load plaster
                if (this.isPlasterInstalled.Value && this.isPlasterLoaded == false)
                {
                    this.logger.Write(LogLevel.Verbose, "Loading Plaster...");

                    psCommand = new PSCommand();
                    psCommand
                    .AddCommand("Import-Module")
                    .AddParameter("ModuleInfo", (PSModuleInfo)moduleObject.ImmediateBaseObject)
                    .AddParameter("PassThru");

                    var importResult =
                        await this.powerShellContext.ExecuteCommandAsync <object>(
                            psCommand, false, false);

                    this.isPlasterLoaded = importResult.Any();
                    string loadedQualifier =
                        this.isPlasterInstalled.Value
                            ? "was" : "could not be";

                    this.logger.Write(
                        LogLevel.Verbose,
                        $"Plaster {loadedQualifier} loaded successfully!");
                }
            }

            return(this.isPlasterInstalled.Value);
        }
Example #29
0
        static int Main(string[] args)
        {
            // Using reflection determine available commands
            Dictionary <Type, CaseInsensitiveList> availableCommands = ReflectionHelper.GetCommands();
            List <PSCommand> userCommands = null;

            // If no arguments are provided to the executable, show help
            if (args.Length == 0)
            {
                Console.WriteLine("== NoPowerShell v{0} ==\r\nWebsite: {1}\r\n{2}", VERSION, WEBSITE, USAGE);
                userCommands = new List <PSCommand>(1)
                {
                    new GetCommandCommand(null)
                };
            }
            // Parse pipes in commandline arguments and commands within pipes
            else
            {
                string error = null;

                try
                {
                    userCommands = PipeParser.ParseArguments(args, availableCommands);
                }
                catch (ParameterBindingException ex)
                {
                    error = ex.Message;
                }
                catch (CommandNotFoundException ex)
                {
                    error = string.Join("", new string[] { ex.Message, HELP });
                }

                if (error != null)
                {
                    WriteError(error);
                    return(-1);
                }
            }

            // Add output to console if no explicit output is provided
            Type lastCommand = userCommands[userCommands.Count - 1].GetType();
            bool justOutput  = false;

            if (lastCommand != typeof(FormatListCommand) && lastCommand != typeof(FormatTableCommand))
            {
                justOutput = true;
            }

            CommandResult result = null;

#if DEBUG
            // Execute commands in pipeline
            foreach (PSCommand command in userCommands)
            {
                result = command.Execute(result);
            }
#else
            PSCommand mostRecentCommand = null;
            try
            {
                // Execute commands in pipeline
                foreach (PSCommand command in userCommands)
                {
                    mostRecentCommand = command;
                    result            = command.Execute(result);
                }
            }
            catch (NoPowerShellException e)
            {
                WriteError(string.Format("{0} : {1}", mostRecentCommand.ToString(), e.Message));
                return(-1);
            }
            catch (Exception e)
            {
                WriteError(string.Format("{0} : {1}", mostRecentCommand.ToString(), e.ToString()));
                return(-1);
            }
#endif

            // Output to screen
            if (justOutput)
            {
                ResultPrinter.OutputResults(result);
            }

            return(0);
        }
Example #30
0
        internal async void OnDebuggerStopAsync(object sender, DebuggerStopEventArgs e)
        {
            bool   noScriptName    = false;
            string localScriptPath = e.InvocationInfo.ScriptName;

            // If there's no ScriptName, get the "list" of the current source
            if (this.remoteFileManager != null && string.IsNullOrEmpty(localScriptPath))
            {
                // Get the current script listing and create the buffer
                PSCommand command = new PSCommand();
                command.AddScript($"list 1 {int.MaxValue}");

                IEnumerable <PSObject> scriptListingLines =
                    await this.powerShellContext.ExecuteCommandAsync <PSObject>(
                        command, false, false).ConfigureAwait(false);

                if (scriptListingLines != null)
                {
                    int linePrefixLength = 0;

                    string scriptListing =
                        string.Join(
                            Environment.NewLine,
                            scriptListingLines
                            .Select(o => DebugService.TrimScriptListingLine(o, ref linePrefixLength))
                            .Where(s => s != null));

                    this.temporaryScriptListingPath =
                        this.remoteFileManager.CreateTemporaryFile(
                            $"[{this.powerShellContext.CurrentRunspace.SessionDetails.ComputerName}] {TemporaryScriptFileName}",
                            scriptListing,
                            this.powerShellContext.CurrentRunspace);

                    localScriptPath =
                        this.temporaryScriptListingPath
                        ?? StackFrameDetails.NoFileScriptPath;

                    noScriptName = localScriptPath != null;
                }
                else
                {
                    this.logger.LogWarning($"Could not load script context");
                }
            }

            // Get call stack and variables.
            await this.FetchStackFramesAndVariablesAsync(
                noScriptName?localScriptPath : null).ConfigureAwait(false);

            // If this is a remote connection and the debugger stopped at a line
            // in a script file, get the file contents
            if (this.powerShellContext.CurrentRunspace.Location == RunspaceLocation.Remote &&
                this.remoteFileManager != null &&
                !noScriptName)
            {
                localScriptPath =
                    await this.remoteFileManager.FetchRemoteFileAsync(
                        e.InvocationInfo.ScriptName,
                        powerShellContext.CurrentRunspace).ConfigureAwait(false);
            }

            if (this.stackFrameDetails.Length > 0)
            {
                // Augment the top stack frame with details from the stop event

                if (this.invocationTypeScriptPositionProperty
                    .GetValue(e.InvocationInfo) is IScriptExtent scriptExtent)
                {
                    this.stackFrameDetails[0].StartLineNumber   = scriptExtent.StartLineNumber;
                    this.stackFrameDetails[0].EndLineNumber     = scriptExtent.EndLineNumber;
                    this.stackFrameDetails[0].StartColumnNumber = scriptExtent.StartColumnNumber;
                    this.stackFrameDetails[0].EndColumnNumber   = scriptExtent.EndColumnNumber;
                }
            }

            this.CurrentDebuggerStoppedEventArgs =
                new DebuggerStoppedEventArgs(
                    e,
                    this.powerShellContext.CurrentRunspace,
                    localScriptPath);

            // Notify the host that the debugger is stopped
            this.DebuggerStopped?.Invoke(
                sender,
                this.CurrentDebuggerStoppedEventArgs);
        }
Example #31
0
        private static string GetPrompt()
        {
            string newPrompt = null;

            try
            {
                if (_singleton._runspace?.Debugger != null && _singleton._runspace.Debugger.InBreakpoint)
                {
                    // Run prompt command in debugger API to ensure it is run correctly on the runspace.
                    // This handles remote runspace debugging and nested debugger scenarios.
                    PSDataCollection <PSObject> results = new PSDataCollection <PSObject>();
                    var command = new PSCommand();
                    command.AddCommand("prompt");
                    _singleton._runspace.Debugger.ProcessCommand(
                        command,
                        results);

                    if (results.Count == 1)
                    {
                        newPrompt = results[0].BaseObject as string;
                    }
                }
                else
                {
                    var runspaceIsRemote = _singleton._mockableMethods.RunspaceIsRemote(_singleton._runspace);

                    System.Management.Automation.PowerShell ps;
                    if (!runspaceIsRemote)
                    {
                        ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
                    }
                    else
                    {
                        ps          = System.Management.Automation.PowerShell.Create();
                        ps.Runspace = _singleton._runspace;
                    }

                    using (ps)
                    {
                        ps.AddCommand("prompt");
                        var result = ps.Invoke <string>();
                        if (result.Count == 1)
                        {
                            newPrompt = result[0];

                            if (runspaceIsRemote)
                            {
                                if (!string.IsNullOrEmpty(_singleton._runspace?.ConnectionInfo?.ComputerName))
                                {
                                    newPrompt = "[" + (_singleton._runspace?.ConnectionInfo).ComputerName + "]: " + newPrompt;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                // Catching all exceptions makes debugging problems a bit harder, but it avoids some noise if
                // the remote doesn't define a prompt.
            }

            if (string.IsNullOrEmpty(newPrompt))
            {
                newPrompt = "PS>";
            }

            return(newPrompt);
        }
Example #32
0
        /// <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;
        }
Example #33
0
        // Нажата кнопка загрузки информации
        private void btLoadInfo_Click(object sender, RoutedEventArgs e)
        {
            #region Проверка и инициализация входных данных
            if (!_userIsSelected)
            {
                MessageBox.Show("Не выбран пользователь!!!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            loadedData.User = loginUser.Text;
            string errorMesg = "";
            #endregion

            Thread t = new Thread(() =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    isEnableForm(false);
                }));

                #region Чтение конфигурационного файла плагина
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Чтение конфигурационного файла плагина...";
                }));
                configData = GetConfigData(_pathToConfig, ref errorMesg);
                if (!string.IsNullOrWhiteSpace(errorMesg))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка чтения конфигурационного файла:\r\n" + errorMesg);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                if (!configData.ContainsKey("mailserver"))
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Отсутсвуют требуемые параметры в конфигурационном файле!!!");
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                //============================================================
                PSCredential credential                = new PSCredential(_login, _password);
                WSManConnectionInfo connectionInfo     = new WSManConnectionInfo((new Uri(configData["mailserver"])), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                Runspace runspace     = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                PowerShell powershell = PowerShell.Create();
                PSCommand command     = new PSCommand();
                //============================================================

                #region Подключение к Exchange Server
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Подключение к Exchange Server...";
                }));
                try
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка подключения к Exchange Server:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка функций почтового ящика
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка функций почтового ящика...";
                }));
                try
                {
                    string[] loadParam = new string[] { "ActiveSyncEnabled", "ActiveSyncMailboxPolicy", "OWAEnabled", "OwaMailboxPolicy", "MAPIEnabled", "PopEnabled", "ImapEnabled" };
                    command.AddCommand("Get-CASMailbox");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);

                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки функций почтового ящика:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        var cmd = result[0];
                        if (cmd.Properties["ActiveSyncEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableActiveSync = true;
                        }
                        else
                        {
                            loadedData.IsEnableActiveSync = false;
                        }
                        if (cmd.Properties["ActiveSyncMailboxPolicy"].Value != null)
                        {
                            loadedData.PolicyActiveSync = cmd.Properties["ActiveSyncMailboxPolicy"].Value.ToString();
                        }
                        else
                        {
                            loadedData.PolicyActiveSync = "";
                        }
                        if (cmd.Properties["OWAEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableWebApp = true;
                        }
                        else
                        {
                            loadedData.IsEnableWebApp = false;
                        }
                        if (cmd.Properties["OwaMailboxPolicy"].Value != null)
                        {
                            loadedData.PolicyWebApp = cmd.Properties["OwaMailboxPolicy"].Value.ToString();
                        }
                        else
                        {
                            loadedData.PolicyWebApp = "";
                        }
                        if (cmd.Properties["MAPIEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableMAPI = true;
                        }
                        else
                        {
                            loadedData.IsEnableMAPI = false;
                        }
                        if (cmd.Properties["PopEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnablePOP = true;
                        }
                        else
                        {
                            loadedData.IsEnablePOP = false;
                        }
                        if (cmd.Properties["ImapEnabled"].Value.ToString().ToUpper() == "TRUE")
                        {
                            loadedData.IsEnableIMAP = true;
                        }
                        else
                        {
                            loadedData.IsEnableIMAP = false;
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки функций почтового ящика:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка переадресации
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка переадресации...";
                }));
                try
                {
                    string[] loadParam = new string[] { "ForwardingAddress", "ForwardingSmtpAddress" };
                    command.AddCommand("Get-Mailbox");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);

                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки переадресации:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        var cmd = result[0];

                        if (cmd.Properties["ForwardingAddress"].Value != null)
                        {
                            loadedData.ForwardingAddress = cmd.Properties["ForwardingAddress"].Value.ToString();
                        }
                        else
                        {
                            loadedData.ForwardingAddress = "";
                        }

                        if (cmd.Properties["ForwardingSmtpAddress"].Value != null)
                        {
                            loadedData.ForwardingSmtpAddress = cmd.Properties["ForwardingSmtpAddress"].Value.ToString();
                        }
                        else
                        {
                            loadedData.ForwardingSmtpAddress = "";
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки переадресации:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка электронных адресов
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка электронных адресов...";
                }));
                try
                {
                    command.AddCommand("Get-Mailbox");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("ExpandProperty", "EmailAddresses");
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки электронных адресов:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        loadedData.EmailAddress = "";
                        for (int i = 0; i < result.Count; i++)
                        {
                            loadedData.EmailAddress += result[i].Properties["ProxyAddressString"].Value.ToString() + "\r\n";
                            if (result[i].Properties["ProxyAddressString"].Value.ToString().StartsWith("SMTP"))
                            {
                                loadedData.PrimaryEmailAddres = result[i].Properties["ProxyAddressString"].Value.ToString().Split(':')[1];
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки электронных адресов:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка правил входящих сообщений
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка правил входящих сообщений...";
                }));
                try
                {
                    string[] loadParam          = new string[] { "Enabled", "Priority", "Name", "Description" };
                    loadedData.IndoxMessageRule = new List <InboxMessageRuleInfo>();
                    command.AddCommand("Get-InboxRule");
                    command.AddParameter("Mailbox", loadedData.PrimaryEmailAddres);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки правил входящих сообщений:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        for (int i = 0; i < result.Count; i++)
                        {
                            var cmd = result[i];
                            loadedData.IndoxMessageRule.Add(new InboxMessageRuleInfo {
                                IsEnabled   = cmd.Properties["Enabled"].Value.ToString().ToUpper() == "TRUE" ? true : false,
                                Priority    = Int32.Parse(cmd.Properties["Priority"].Value.ToString()),
                                Name        = cmd.Properties["Name"].Value.ToString(),
                                Description = cmd.Properties["Description"].Value.ToString()
                            });
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки правил входящих сообщений:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка информации по установленному автоответу
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка информации по установленному автоответу...";
                }));
                try
                {
                    string[] loadParam    = new string[] { "AutoReplyState", "StartTime", "EndTime", "InternalMessage", "ExternalMessage" };
                    loadedData.AutoReplay = new UserAutoReplayInfo();
                    command.AddCommand("Get-MailboxAutoReplyConfiguration");
                    command.AddParameter("Identity", loadedData.User);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки информации по установленному автоответу:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        loadedData.AutoReplay = new UserAutoReplayInfo()
                        {
                            State               = result[0].Properties["AutoReplyState"].Value.ToString(),
                            StartDateTime       = DateTime.ParseExact(result[0].Properties["StartTime"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture),
                            EndDateTime         = DateTime.ParseExact(result[0].Properties["EndTime"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture),
                            InternalMessageText = result[0].Properties["InternalMessage"].Value != null ? result[0].Properties["InternalMessage"].Value.ToString() : "",
                            ExternalMessageText = result[0].Properties["ExternalMessage"].Value != null ? result[0].Properties["ExternalMessage"].Value.ToString() : ""
                        };
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка загрузки информации по установленному автоответу:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                #region Загрузка информации по мобильным устройствам
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "Загрузка информации по мобильным устройствам...";
                }));
                try
                {
                    string[] loadParam      = new string[] { "DeviceType", "DeviceFriendlyName", "DeviceModel", "DeviceUserAgent", "LastSyncAttemptTime", "LastSuccessSync" };
                    loadedData.MobileDevice = new List <MobileDeviceInfo>();
                    command.AddCommand("Get-ActiveSyncDeviceStatistics");
                    command.AddParameter("Mailbox", loadedData.PrimaryEmailAddres);
                    command.AddCommand("Select-Object");
                    command.AddParameter("Property", loadParam);
                    powershell.Commands = command;
                    var result          = powershell.Invoke();
                    command.Clear();
                    if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
                    {
                        for (int i = 0; i < powershell.Streams.Error.Count; i++)
                        {
                            string errorMsg = "Ошибка загрузки информации по мобильным устройствам:\r\n" + powershell.Streams.Error[i].ToString();
                            Dispatcher.BeginInvoke(new Action(() =>
                            {
                                _errorMessages.Add(errorMsg);
                            }));
                        }
                        runspace.Dispose();
                        runspace = null;
                        powershell.Dispose();
                        powershell = null;
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                            isEnableForm(true);
                        }));
                        return;
                    }
                    if (result.Count > 0)
                    {
                        for (int i = 0; i < result.Count; i++)
                        {
                            var cmd = result[i];
                            loadedData.MobileDevice.Add(new MobileDeviceInfo
                            {
                                DeviceType          = cmd.Properties["DeviceType"].Value != null ? cmd.Properties["DeviceType"].Value.ToString() : "",
                                DeviceName          = cmd.Properties["DeviceFriendlyName"].Value != null ? cmd.Properties["DeviceFriendlyName"].Value.ToString() : "",
                                DeviceModel         = cmd.Properties["DeviceModel"].Value != null ? cmd.Properties["DeviceModel"].Value.ToString() : "",
                                DeviceUserAgent     = cmd.Properties["DeviceUserAgent"].Value != null ? cmd.Properties["DeviceUserAgent"].Value.ToString() : "",
                                LastSuccessSyncTime = cmd.Properties["LastSyncAttemptTime"].Value != null ? DateTime.ParseExact(cmd.Properties["LastSyncAttemptTime"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture) : (DateTime?)null,
                                LastSyncTime        = cmd.Properties["LastSuccessSync"].Value != null ? DateTime.ParseExact(cmd.Properties["LastSuccessSync"].Value.ToString(), "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture) : (DateTime?)null
                            });
                        }
                    }
                }
                catch (Exception exp)
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _errorMessages.Add("Ошибка информации по мобильным устройствам:\r\n" + exp.Message);
                        statusBarText.Content = "В процессе загрузки возникли ошибки!!!";
                        isEnableForm(true);
                    }));
                    return;
                }
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    statusBarText.Content = "";
                }));
                #endregion

                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
                command.Clear();
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    setLoadedData(loadedData);
                    isEnableForm(true);
                }));
            });
            t.IsBackground = true;
            t.Start();
        }