Пример #1
0
        /// <summary>
        /// Gets the CommandInfo instance for a command with a particular name.
        /// </summary>
        /// <param name="commandName">The name of the command.</param>
        /// <param name="powerShellContext">The PowerShellContext to use for running Get-Command.</param>
        /// <returns>A CommandInfo object with details about the specified command.</returns>
        public static async Task <CommandInfo> GetCommandInfoAsync(
            string commandName,
            PowerShellContextService powerShellContext)
        {
            Validate.IsNotNull(nameof(commandName), commandName);
            Validate.IsNotNull(nameof(powerShellContext), powerShellContext);

            // Make sure the command's noun isn't blacklisted.  This is
            // currently necessary to make sure that Get-Command doesn't
            // load PackageManagement or PowerShellGet because they cause
            // a major slowdown in IntelliSense.
            var commandParts = commandName.Split('-');

            if (commandParts.Length == 2 && NounExclusionList.ContainsKey(commandParts[1]))
            {
                return(null);
            }

            PSCommand command = new PSCommand();

            command.AddCommand(@"Microsoft.PowerShell.Core\Get-Command");
            command.AddArgument(commandName);
            command.AddParameter("ErrorAction", "Ignore");

            return((await powerShellContext.ExecuteCommandAsync <PSObject>(command, sendOutputToHost: false, sendErrorToHost: false).ConfigureAwait(false))
                   .Select(o => o.BaseObject)
                   .OfType <CommandInfo>()
                   .FirstOrDefault());
        }
Пример #2
0
        private PSCommand RegisterCommand(Match match, PSCommand cmdlet, string cmdletNameGroup, string parameterSetGroup)
        {
            cmdlet.AddCommand(new Command(match.Groups[cmdletNameGroup].Value, false, true));
            CaptureCollection captures = match.Groups[parameterSetGroup].Captures;

            string[] array = new string[captures.Count];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = captures[i].Value;
            }
            int j = 0;

            while (j < array.Length)
            {
                if (j == 0 && !array[j].StartsWith("-"))
                {
                    cmdlet.AddArgument(array[j]);
                    j++;
                }
                else if (j + 1 == array.Length || (j + 1 < array.Length && array[j + 1].StartsWith("-")))
                {
                    cmdlet.AddParameter(array[j].Substring(1), true);
                    j++;
                }
                else
                {
                    cmdlet.AddParameter(array[j].Substring(1), this.UnwrapValue(array[j + 1]));
                    j += 2;
                }
            }
            return(cmdlet);
        }
Пример #3
0
        public List <string> GetManagedBy(string groupname)
        {
            var ret = new List <string>();

            var runspace   = this.CreateRunspace();
            var powershell = PowerShell.Create();
            var command    = new PSCommand();

            command.AddCommand("Get-DistributionGroup");
            command.AddArgument(groupname);
            command.AddCommand("Select-Object");
            command.AddParameter("Property", "ManagedBy");
            powershell.Commands = command;
            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                Collection <PSObject> results = powershell.Invoke();

                this._log.Info(JsonConvert.SerializeObject(results));

                if (results != null)
                {
                    if (results.Count > 0)
                    {
                        for (int i = 0; i < results.Count; i++)
                        {
                            if (results[i].Properties.Any(property => property.Name == "ManagedBy"))
                            {
                                var users =
                                    (ArrayList)
                                    ((System.Management.Automation.PSObject)
                                         (results[0].Properties["ManagedBy"].Value)).BaseObject;
                                ret.AddRange(from object user in users select user.ToString() into name select name.Contains("/") ? name.Substring(name.LastIndexOf("/", StringComparison.Ordinal) + 1) : name);
                            }
                        }
                    }
                    else
                    {
                        this._log.Info(command.Commands[0].CommandText);
                    }
                }
                return(ret);
            }
            catch (Exception ex)
            {
                return(ret);
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
        }
Пример #4
0
        public List <string> GetDistributionGroupMember(string groupname)
        {
            var ret = new List <string>();

            var runspace   = this.CreateRunspace();
            var powershell = PowerShell.Create();
            var command    = new PSCommand();

            command.AddCommand("Get-DistributionGroupMember");
            command.AddArgument(groupname);
            powershell.Commands = command;

            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                Collection <PSObject> results = powershell.Invoke();
                if (results != null)
                {
                    if (results.Count > 0)
                    {
                        this._log.Info("Succeed in Executing the Remote Powershell Command:");
                        this._log.Info(command.Commands[0].CommandText);

                        for (int i = 0; i < results.Count; i++)
                        {
                            foreach (PSPropertyInfo property in results[i].Properties)
                            {
                                if (property.Name == "Name")
                                {
                                    ret.Add(property.Value.ToString());
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        this._log.Info("No result resturned in Executing the Remote Powershell Command: ");
                        this._log.Info(command.Commands[0].CommandText);
                    }
                }
            }
            catch (Exception ex)
            {
                this._log.Error("获取组成员失败", ex);
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
            return(ret);
        }
        private async Task <CommandInfo> GetCommandInfo(string commandName)
        {
            PSCommand command = new PSCommand();

            command.AddCommand("Get-Command");
            command.AddArgument(commandName);

            var results = await this.powerShellContext.ExecuteCommand <CommandInfo>(command);

            return(results.FirstOrDefault());
        }
        /// <summary>
        /// Parse a PowerShell text string into a PSCommand with parameters
        /// This is a very basic parser and won't work with complex cmdlet calls
        /// </summary>
        /// <param name="commandLine">The PowerShell code</param>
        private PSCommand ParseCommand(string commandLine)
        {
            PSCommand command = new PSCommand();
            int       i       = commandLine.IndexOf(" ");

            if (i < 0)
            {
                // The command has no parameters, so add as is
                command.AddCommand(commandLine);
                return(command);
            }

            // Add the command, then we need to deal with parameters

            command.AddCommand(commandLine.Substring(0, i));
            string parameters = commandLine.Substring(i + 1);

            i = parameters.IndexOf("-", i);
            if (i < 0)
            {
                // We have parameters, but they are not named - we just add them to the command
                command.AddArgument(parameters);
                return(command);
            }

            // Now parse and add parameters
            try
            {
                while ((i > 0) && (i < commandLine.Length))
                {
                    int j = parameters.IndexOf("-", i + 1);
                    if (j < 0)
                    {
                        j = parameters.Length;
                    }
                    int    p           = parameters.IndexOf(" ", i + 1);
                    string sParamName  = parameters.Substring(i + 1, p - i - 1);
                    string sParamValue = parameters.Substring(p + 1, j - p - 2).Trim();
                    if (sParamValue.StartsWith("\"") && sParamValue.EndsWith("\""))
                    {
                        sParamValue = sParamValue.Substring(1, sParamValue.Length - 2);
                    }
                    command.AddParameter(sParamName, sParamValue);
                    i = j;
                }
            }
            catch (Exception ex)
            {
                LogError(String.Format("Unable to parse command parameters: {0}", ex.Message));
            }
            return(command);
        }
        /// <summary>
        /// Gets the CommandInfo instance for a command with a particular name.
        /// </summary>
        /// <param name="commandName">The name of the command.</param>
        /// <param name="powerShellContext">The PowerShellContext to use for running Get-Command.</param>
        /// <returns>A CommandInfo object with details about the specified command.</returns>
        public static async Task <CommandInfo> GetCommandInfo(
            string commandName,
            PowerShellContext powerShellContext)
        {
            PSCommand command = new PSCommand();

            command.AddCommand(@"Microsoft.PowerShell.Core\Get-Command");
            command.AddArgument(commandName);

            var results = await powerShellContext.ExecuteCommand <CommandInfo>(command, false, false);

            return(results.FirstOrDefault());
        }
Пример #8
0
        public CommandResult SetRequireSenderAuthenticationEnabled(string groupname, bool enable)
        {
            var ret = new CommandResult();

            var runspace   = this.CreateRunspace();
            var powershell = PowerShell.Create();
            var command    = new PSCommand();

            command.AddCommand("Set-DistributionGroup");
            command.AddArgument(groupname);
            command.AddParameter("RequireSenderAuthenticationEnabled", enable ? 1 : 0);
            powershell.Commands = command;
            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                Collection <PSObject> results = powershell.Invoke();

                if (results != null)
                {
                    var retCheck = this.GetRequireSenderAuthenticationEnabled(groupname);
                    if (retCheck.Success && retCheck.Message.ToUpper() == enable.ToString().ToUpper())
                    {
                        ret.Success = true;
                        ret.Message = "设置属性成功";
                    }
                    else
                    {
                        ret.Success = false;
                        ret.Message = "设置属性失败";
                    }
                }

                return(ret);
            }
            catch (Exception ex)
            {
                return(new CommandResult()
                {
                    Success = false, Message = $"消息:{ex.Message}    堆栈:{ex.StackTrace}"
                });
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
        }
Пример #9
0
        public CommandResult GetRequireSenderAuthenticationEnabled(string groupname)
        {
            var ret = new CommandResult();

            var runspace   = this.CreateRunspace();
            var powershell = PowerShell.Create();
            var command    = new PSCommand();

            command.AddCommand("Get-DistributionGroup");
            command.AddArgument(groupname);
            command.AddCommand("Select-Object");
            command.AddParameter("Property", "RequireSenderAuthenticationEnabled");

            powershell.Commands = command;

            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                Collection <PSObject> results = powershell.Invoke();

                if (results != null && results.Count > 0)
                {
                    ret.Success = true;
                    ret.Message = results[0].Properties["RequireSenderAuthenticationEnabled"].Value.ToString();
                }
                else
                {
                    ret.Success = false;
                    ret.Message = "获取属性失败";
                }
                return(ret);
            }
            catch (Exception ex)
            {
                return(new CommandResult()
                {
                    Success = false, Message = $"消息:{ex.Message}    堆栈:{ex.StackTrace}"
                });
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
        }
Пример #10
0
        /// <summary>
        /// Gets the CommandInfo instance for a command with a particular name.
        /// </summary>
        /// <param name="commandName">The name of the command.</param>
        /// <param name="powerShellContext">The PowerShellContext to use for running Get-Command.</param>
        /// <returns>A CommandInfo object with details about the specified command.</returns>
        public static async Task <CommandInfo> GetCommandInfo(
            string commandName,
            PowerShellContext powerShellContext)
        {
            PSCommand command = new PSCommand();

            command.AddCommand(@"Microsoft.PowerShell.Core\Get-Command");
            command.AddArgument(commandName);

            return
                ((await powerShellContext
                  .ExecuteCommand <PSObject>(command, false, false))
                 .Select(o => o.BaseObject)
                 .OfType <CommandInfo>()
                 .FirstOrDefault());
        }
Пример #11
0
        public List <string> GetGrantSendOnBehalfTo(string groupname)
        {
            var ret = new List <string>();

            var runspace   = this.CreateRunspace();
            var powershell = PowerShell.Create();
            var command    = new PSCommand();

            command.AddCommand("Get-DistributionGroup");
            command.AddArgument(groupname);
            command.AddCommand("Select-Object");
            command.AddParameter("Property", "GrantSendOnBehalfTo");
            powershell.Commands = command;
            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                Collection <PSObject> results = powershell.Invoke();
                if (results != null)
                {
                    foreach (PSObject obj in results)
                    {
                        if (obj.Properties.Any(property => property.Name == "GrantSendOnBehalfTo"))
                        {
                            var users =
                                (ArrayList)
                                ((System.Management.Automation.PSObject)
                                     (results[0].Properties["GrantSendOnBehalfTo"].Value)).BaseObject;
                            ret.AddRange(from object user in users select user.ToString() into name select name.Contains("/") ? name.Substring(name.LastIndexOf("/", StringComparison.Ordinal) + 1) : name);
                        }
                    }
                }
                return(ret);
            }
            catch (Exception ex)
            {
                return(ret);
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
        }
Пример #12
0
        /// <summary>
        /// Gets the CommandInfo instance for a command with a particular name.
        /// </summary>
        /// <param name="commandName">The name of the command.</param>
        /// <param name="powerShellContext">The PowerShellContext to use for running Get-Command.</param>
        /// <returns>A CommandInfo object with details about the specified command.</returns>
        public static async Task <CommandInfo> GetCommandInfoAsync(
            string commandName,
            PowerShellContextService powerShellContext)
        {
            Validate.IsNotNull(nameof(commandName), commandName);
            Validate.IsNotNull(nameof(powerShellContext), powerShellContext);

            // If we have a CommandInfo cached, return that.
            if (s_commandInfoCache.TryGetValue(commandName, out CommandInfo cmdInfo))
            {
                return(cmdInfo);
            }

            // Make sure the command's noun or command's name isn't in the exclusion lists.
            // This is currently necessary to make sure that Get-Command doesn't
            // load PackageManagement or PowerShellGet v2 because they cause
            // a major slowdown in IntelliSense.
            var commandParts = commandName.Split('-');

            if ((commandParts.Length == 2 && s_nounExclusionList.Contains(commandParts[1])) ||
                s_cmdletExclusionList.Contains(commandName))
            {
                return(null);
            }

            PSCommand command = new PSCommand();

            command.AddCommand(@"Microsoft.PowerShell.Core\Get-Command");
            command.AddArgument(commandName);
            command.AddParameter("ErrorAction", "Ignore");

            CommandInfo commandInfo = (await powerShellContext.ExecuteCommandAsync <PSObject>(command, sendOutputToHost: false, sendErrorToHost: false).ConfigureAwait(false))
                                      .Select(o => o.BaseObject)
                                      .OfType <CommandInfo>()
                                      .FirstOrDefault();

            // Only cache CmdletInfos since they're exposed in binaries they are likely to not change throughout the session.
            if (commandInfo?.CommandType == CommandTypes.Cmdlet)
            {
                s_commandInfoCache.TryAdd(commandName, commandInfo);
            }

            return(commandInfo);
        }
        protected async Task HandleShowOnlineHelpRequest(
            string helpParams,
            RequestContext <object> requestContext)
        {
            if (helpParams == null)
            {
                helpParams = "get-help";
            }

            var psCommand = new PSCommand();

            psCommand.AddCommand("Get-Help");
            psCommand.AddArgument(helpParams);
            psCommand.AddParameter("Online");

            await editorSession.PowerShellContext.ExecuteCommand <object>(psCommand);

            await requestContext.SendResult(null);
        }
Пример #14
0
        public CommandResult AddDistributionGroupMember(string groupname, string membername)
        {
            var ret = new CommandResult();

            var runspace   = this.CreateRunspace();
            var powershell = PowerShell.Create();
            var command    = new PSCommand();

            command.AddCommand("ADD-DistributionGroupMember");
            command.AddArgument(groupname);
            command.AddParameter("Member", membername);


            powershell.Commands = command;
            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                Collection <PSObject> results = powershell.Invoke();

                if (results != null)
                {
                    var membernames = this.GetDistributionGroupMember(groupname);
                    ret.Success = membernames.Contains(membername);
                }

                return(ret);
            }
            catch (Exception ex)
            {
                return(new CommandResult()
                {
                    Success = false, Message = $"消息:{ex.Message}    堆栈:{ex.StackTrace}"
                });
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
        }
        /// <summary>
        /// Gets the command's "Synopsis" documentation section.
        /// </summary>
        /// <param name="commandInfo">The CommandInfo instance for the command.</param>
        /// <param name="powerShellContext">The PowerShellContext to use for getting command documentation.</param>
        /// <returns></returns>
        public static async Task <string> GetCommandSynopsis(
            CommandInfo commandInfo,
            PowerShellContext powerShellContext)
        {
            string synopsisString = string.Empty;

            PSObject helpObject = null;

            if (commandInfo != null &&
                (commandInfo.CommandType == CommandTypes.Cmdlet ||
                 commandInfo.CommandType == CommandTypes.Function ||
                 commandInfo.CommandType == CommandTypes.Filter))
            {
                PSCommand command = new PSCommand();
                command.AddCommand(@"Microsoft.PowerShell.Core\Get-Help");
                command.AddArgument(commandInfo);
                command.AddParameter("ErrorAction", "Ignore");

                var results = await powerShellContext.ExecuteCommand <PSObject>(command, false, false);

                helpObject = results.FirstOrDefault();

                if (helpObject != null)
                {
                    // Extract the synopsis string from the object
                    synopsisString =
                        (string)helpObject.Properties["synopsis"].Value ??
                        string.Empty;

                    // Ignore the placeholder value for this field
                    if (string.Equals(synopsisString, "SHORT DESCRIPTION", System.StringComparison.CurrentCultureIgnoreCase))
                    {
                        synopsisString = string.Empty;
                    }
                }
            }

            return(synopsisString);
        }
        private static void AddParameters(this PSCommand psCommand, IEnumerable <KeyValuePair <string, object> > parameters)
        {
            string key;

            if (parameters == null)
            {
                return;
            }

            foreach (var kvp in parameters)
            {
                key = (kvp.Key == null) ? string.Empty : kvp.Key.Trim();

                if (key.Length > 0)
                {
                    psCommand.AddParameter(key, kvp.Value);
                }
                else
                if (kvp.Value != null)
                {
                    psCommand.AddArgument(kvp.Value);
                }
            }
        }
Пример #17
0
        private void SetCommandsAndScripts(ref PSCommand oCommand)
        {
            // Command 1 ------------------------------------
            if (chkCommand1.Checked == true)
            {
                oCommand.AddCommand(txtCommand1.Text.Trim());

                if (this.txtArgument1x1.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.txtArgument1x1.Text.Trim());
                }
                if (this.txtArgument1x2.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.txtArgument1x2.Text.Trim());
                }
                if (this.txtArgument1x3.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.txtArgument1x3.Text.Trim());
                }


                if (txtParamName1x1.Text.Trim().Length != 0)
                {
                    if (txtParamValue1x1.Text.Trim().Length != 0)
                    {
                        oCommand.AddParameter(txtParamName1x1.Text.Trim(), txtParamValue1x1.Text.Trim());
                    }
                    else
                    {
                        oCommand.AddParameter(txtParamName1x1.Text.Trim());
                    }
                }

                if (txtParamName1x2.Text.Trim().Length != 0)
                {
                    if (txtParamValue1x2.Text.Trim().Length != 0)
                    {
                        oCommand.AddParameter(txtParamName1x2.Text.Trim(), txtParamValue1x2.Text.Trim());
                    }
                    else
                    {
                        oCommand.AddParameter(txtParamName1x2.Text.Trim());
                    }
                }

                if (txtParamName1x3.Text.Trim().Length != 0)
                {
                    if (txtParamValue1x3.Text.Trim().Length != 0)
                    {
                        oCommand.AddParameter(txtParamName1x3.Text.Trim(), txtParamValue1x3.Text.Trim());
                    }
                    else
                    {
                        oCommand.AddParameter(txtParamName1x3.Text.Trim());
                    }
                }
            }

            // Script 1 ------------------------------------

            if (chkScript1.Checked == true)
            {
                oCommand.Commands.AddScript(txtScript1.Text.Trim(), chkScript1UseLocalScope.Checked);

                if (this.Script1Arg1.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script1Arg1.Text.Trim());
                }
                if (this.Script1Arg2.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script1Arg2.Text.Trim());
                }
                if (this.Script1Arg3.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script1Arg3.Text.Trim());
                }
                if (this.Script1Arg4.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script1Arg4.Text.Trim());
                }
            }

            // Command 2 ------------------------------------
            if (chkCommand2.Checked == true)
            {
                oCommand.AddCommand(txtCommand2.Text.Trim());

                /// Arguments
                if (this.txtArgument2x1.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.txtArgument2x1.Text.Trim());
                }
                if (this.txtArgument2x2.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.txtArgument2x2.Text.Trim());
                }
                if (this.txtArgument2x3.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.txtArgument2x3.Text.Trim());
                }
                if (this.txtArgument2x4.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.txtArgument2x4.Text.Trim());
                }

                if (txtParamName2x1.Text.Trim().Length != 0)
                {
                    if (txtParamValue2x1.Text.Trim().Length != 0)
                    {
                        oCommand.AddParameter(txtParamName2x1.Text.Trim(), txtParamValue2x1.Text.Trim());
                    }
                    else
                    {
                        oCommand.AddParameter(txtParamName2x1.Text.Trim());
                    }
                }

                if (txtParamName2x2.Text.Trim().Length != 0)
                {
                    if (txtParamValue2x2.Text.Trim().Length != 0)
                    {
                        oCommand.AddParameter(txtParamName2x2.Text.Trim(), txtParamValue2x2.Text.Trim());
                    }
                    else
                    {
                        oCommand.AddParameter(txtParamName2x2.Text.Trim());
                    }
                }

                if (txtParamName2x3.Text.Trim().Length != 0)
                {
                    if (txtParamValue2x3.Text.Trim().Length != 0)
                    {
                        oCommand.AddParameter(txtParamName2x3.Text.Trim(), txtParamValue2x3.Text.Trim());
                    }
                    else
                    {
                        oCommand.AddParameter(txtParamName2x3.Text.Trim());
                    }
                }
            }

            // Script 2 ------------------------------------

            if (chkScript2.Checked == true)
            {
                oCommand.Commands.AddScript(txtScript2.Text.Trim(), chkScript2UseLocalScope.Checked);

                if (this.Script2Arg1.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script2Arg1.Text.Trim());
                }
                if (this.Script2Arg2.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script2Arg2.Text.Trim());
                }
                if (this.Script2Arg3.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script2Arg3.Text.Trim());
                }
                if (this.Script2Arg4.Text.Trim().Length != 0)
                {
                    oCommand.AddArgument(this.Script2Arg4.Text.Trim());
                }
            }
        }
Пример #18
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
        }
Пример #19
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));
            }
        }