/// <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.LogTrace("Checking if Plaster is installed...");

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

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

                this.logger.LogTrace($"Plaster is {installedQualifier}installed!");

                // Attempt to load plaster
                if (this.isPlasterInstalled.Value && this.isPlasterLoaded == false)
                {
                    this.logger.LogTrace("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).ConfigureAwait(false);

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

                    this.logger.LogTrace($"Plaster {loadedQualifier} loaded successfully!");
                }
            }

            return(this.isPlasterInstalled.Value);
        }
Example #2
0
        /// <summary>
        /// Creates the PSCommand when the runspace is not overridden.
        /// </summary>
        private PSCommand CreatePsCommandNotOverridden(string line, bool isScript, bool?useNewScope)
        {
            PSCommand command = new PSCommand();

            if (isScript)
            {
                if (useNewScope.HasValue)
                {
                    command.AddScript(line, useNewScope.Value);
                }
                else
                {
                    command.AddScript(line);
                }
            }
            else
            {
                if (useNewScope.HasValue)
                {
                    command.AddCommand(line, useNewScope.Value);
                }
                else
                {
                    command.AddCommand(line);
                }
            }

            return(command);
        }
Example #3
0
        public static void SetFolderPermissions(string mailbox, string folder, string user, string accessRights)
        {
            PSCommand commands = new PSCommand();

            if (folder == "\\Top of Information Store")
            {
                folder = "\\";
            }
            string folderPath = mailbox + ":" + folder;

            commands.AddCommand("Set-MailboxFolderPermission");
            commands.AddParameter("Identity", folderPath);
            commands.AddParameter("User", user);
            commands.AddParameter("AccessRights", accessRights);
            Collection <PSObject> result1 = runPowershellCommands(commands);

            if (result1.Count == 0)
            {
                commands.Clear();
                commands.AddCommand("Add-MailboxFolderPermission");
                commands.AddParameter("Identity", folderPath);
                commands.AddParameter("User", user);
                commands.AddParameter("AccessRights", accessRights);
                Collection <PSObject> result2 = runPowershellCommands(commands);
            }
        }
Example #4
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;
            }
        }
        private async Task ClearCommandBreakpoints()
        {
            PSCommand psCommand = new PSCommand();

            psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-PSBreakpoint");
            psCommand.AddParameter("Type", "Command");
            psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Remove-PSBreakpoint");

            await this.powerShellContext.ExecuteCommand <object>(psCommand);
        }
Example #6
0
        /// <summary>
        /// Gets a list of message tracking logs between a time period for sent messages
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public List <Models.MessageTrackingLog> Get_TotalSentMessages(DateTime start, DateTime end)
        {
            List <Models.MessageTrackingLog> totalSentMessages = new List <Models.MessageTrackingLog>();

            PSCommand cmd = new PSCommand();

            if (Config.ServiceSettings.ExchangeVersion >= 2013)
            {
                cmd.AddCommand("Get-TransportService");
            }
            else
            {
                cmd.AddCommand("Get-TransportServer");
            }

            cmd.AddCommand("Get-MessageTrackingLog");
            cmd.AddParameter("EventId", "RECEIVE");
            cmd.AddParameter("Start", start.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture));
            cmd.AddParameter("End", end.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture));
            cmd.AddParameter("ResultSize", "Unlimited");
            cmd.AddParameter("DomainController", Config.ServiceSettings.PrimaryDC);
            _powershell.Commands = cmd;

            Collection <PSObject> psObjects = _powershell.Invoke();

            if (_powershell.HadErrors)
            {
                throw _powershell.Streams.Error[0].Exception;
            }
            else
            {
                foreach (PSObject ps in psObjects)
                {
                    Models.MessageTrackingLog newLog = new Models.MessageTrackingLog();
                    newLog.Timestamp      = DateTime.Parse(ps.Members["Timestamp"].Value.ToString());
                    newLog.ServerHostname = ps.Members["ServerHostname"].Value.ToString();
                    newLog.Source         = ps.Members["Source"].Value.ToString();
                    newLog.EventId        = ps.Members["EventId"].Value.ToString();
                    newLog.TotalBytes     = long.Parse(ps.Members["TotalBytes"].Value.ToString());

                    newLog.Users = new List <string>();
                    newLog.Users.Add(ps.Members["Sender"].Value.ToString());

                    if (newLog.Source.Equals("STOREDRIVER"))
                    {
                        totalSentMessages.Add(newLog);
                    }
                }
            }

            return(totalSentMessages);
        }
        /// <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);
        }
Example #8
0
        /// <summary>
        /// Gets a list of message tracking logs between a time period for received messages
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public List <Models.MessageTrackingLog> Get_TotalReceivedMessages(DateTime start, DateTime end)
        {
            List <Models.MessageTrackingLog> totalReceivedMessages = new List <Models.MessageTrackingLog>();

            PSCommand cmd = new PSCommand();

            if (Config.ServiceSettings.ExchangeVersion >= 2013)
            {
                cmd.AddCommand("Get-TransportService");
            }
            else
            {
                cmd.AddCommand("Get-TransportServer");
            }
            cmd.AddCommand("Get-MessageTrackingLog");
            cmd.AddParameter("EventId", "DELIVER");
            cmd.AddParameter("Start", start.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture));
            cmd.AddParameter("End", end.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture));
            cmd.AddParameter("ResultSize", "Unlimited");
            cmd.AddParameter("DomainController", Config.ServiceSettings.PrimaryDC);
            _powershell.Commands = cmd;

            Collection <PSObject> psObjects = _powershell.Invoke();

            if (_powershell.HadErrors)
            {
                throw _powershell.Streams.Error[0].Exception;
            }
            else
            {
                foreach (PSObject ps in psObjects)
                {
                    Models.MessageTrackingLog newLog = new Models.MessageTrackingLog();
                    newLog.Timestamp      = DateTime.Parse(ps.Members["Timestamp"].Value.ToString());
                    newLog.ServerHostname = ps.Members["ServerHostname"].Value.ToString();
                    newLog.Source         = ps.Members["Source"].Value.ToString();
                    newLog.EventId        = ps.Members["EventId"].Value.ToString();
                    newLog.TotalBytes     = long.Parse(ps.Members["TotalBytes"].Value.ToString());

                    var multiValue = ps.Members["Recipients"].Value as PSObject;
                    var users      = multiValue.BaseObject as ArrayList;
                    var array      = users.ToArray(typeof(string)) as string[];
                    newLog.Users = array.ToList();

                    totalReceivedMessages.Add(newLog);
                }
            }

            return(totalReceivedMessages);
        }
Example #9
0
        public List <MessageLog> GetReceiveLog(string reveive, DateTime startTime, DateTime endTime, string subject)
        {
            var ret = new List <MessageLog>();

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

            command.AddCommand("get-transportservice");
            command.AddCommand("get-messagetrackinglog");
            command.AddParameter("Recipients", reveive);
            command.AddParameter("Start", startTime.ToString("yyyy/MM/dd HH:mm:ss"));
            command.AddParameter("End", endTime.ToString("yyyy/MM/dd HH:mm:ss"));
            command.AddParameter("MessageSubject", subject);
            command.AddCommand("Select-Object");
            command.AddParameter("Property", new string[] { "Timestamp", "EventId", "Source", "MessageSubject", "ServerIp", "ServerHostname" });
            powershell.Commands = command;

            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                Collection <PSObject> results = powershell.Invoke();
                if (results != null)
                {
                    foreach (var psobj in results)
                    {
                        var log = new MessageLog();
                        log.Timestamp      = psobj.Properties["Timestamp"].Value.ToString();
                        log.EventId        = psobj.Properties["EventId"].Value.ToString();
                        log.Source         = psobj.Properties["Source"].Value.ToString();
                        log.MessageSubject = psobj.Properties["MessageSubject"].Value.ToString();
                        log.ServerIp       = psobj.Properties["ServerIp"].Value.ToString();
                        log.ServerHostname = psobj.Properties["ServerHostname"].Value.ToString();
                        ret.Add(log);
                    }
                }
            }
            catch (Exception ex)
            {
                this._log.Error("获取发送日志失败", ex);
            }
            finally
            {
                runspace.Dispose();
                powershell.Dispose();
            }
            return(ret);
        }
Example #10
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;
            }
        }
Example #11
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());
        }
        public void Should_UpdateEntry()
        {
            _powerShell.Commands.Clear();
            var mySM = new MockServiceManager();

            ServiceManager.Provider = () => mySM;

            var hfe = new HostFileEntry()
            {
                Address  = "127.0.0.2",
                Hostname = "abc.com"
            };

            mySM.SetupExistingHostList(new [] { hfe });

            PSCommand psCmd = new PSCommand();

            psCmd.AddCommand("Set-HfHostAddress");
            psCmd.AddParameter("Hostname", hfe.Hostname);
            psCmd.AddParameter("Address", "11.11.11.11");

            _powerShell.Commands = psCmd;
            _powerShell.Invoke();

            mySM.MockFileService.Verify(h => h.WriteEntries(
                                            It.Is <IEnumerable <HostFileEntry> >(en => en.Any(writeEntry =>
                                                                                              string.Compare(writeEntry.Hostname, hfe.Hostname) == 0 &&
                                                                                              string.Compare(writeEntry.Address, "11.11.11.11") == 0))));

            // END FUNCTION
        }
Example #13
0
        public async Task <List <PSCommandMessage> > Handle(GetCommandParams request, CancellationToken cancellationToken)
        {
            PSCommand psCommand = new PSCommand();

            // Executes the following:
            // Get-Command -CommandType Function,Cmdlet,ExternalScript | Select-Object -Property Name,ModuleName | Sort-Object -Property Name
            psCommand
            .AddCommand("Microsoft.PowerShell.Core\\Get-Command")
            .AddParameter("CommandType", new[] { "Function", "Cmdlet", "ExternalScript" })
            .AddCommand("Microsoft.PowerShell.Utility\\Select-Object")
            .AddParameter("Property", new[] { "Name", "ModuleName" })
            .AddCommand("Microsoft.PowerShell.Utility\\Sort-Object")
            .AddParameter("Property", "Name");

            IEnumerable <PSObject> result = await _powerShellContextService.ExecuteCommandAsync <PSObject>(psCommand);

            var commandList = new List <PSCommandMessage>();

            if (result != null)
            {
                foreach (dynamic command in result)
                {
                    commandList.Add(new PSCommandMessage
                    {
                        Name                = command.Name,
                        ModuleName          = command.ModuleName,
                        Parameters          = command.Parameters,
                        ParameterSets       = command.ParameterSets,
                        DefaultParameterSet = command.DefaultParameterSet
                    });
                }
            }

            return(commandList);
        }
 void IOrganizationOperation.InvokeOrganizationCmdlet(string organizationId, string cmdlet, bool configOnly)
 {
     using (AnchorRunspaceProxy anchorRunspaceProxy = AnchorRunspaceProxy.CreateRunspaceForDatacenterAdmin(this.Context, "upgradehandlers"))
     {
         PSCommand pscommand = new PSCommand();
         pscommand.AddCommand(cmdlet);
         pscommand.AddParameter("Identity", organizationId);
         if (configOnly && cmdlet.Contains("Start-OrganizationUpgrade"))
         {
             pscommand.AddParameter("ConfigOnly");
         }
         try
         {
             anchorRunspaceProxy.RunPSCommand <PSObject>(pscommand);
         }
         catch (MigrationPermanentException ex)
         {
             this.Context.Logger.Log(MigrationEventType.Error, "{0} '{1}' failed due to {2}", new object[]
             {
                 cmdlet,
                 organizationId,
                 ex
             });
             throw;
         }
     }
 }
 void IOrganizationOperation.SetTenantUpgradeCapability(string identity, bool tenantUpgradeCapabilityEnabled)
 {
     using (AnchorRunspaceProxy anchorRunspaceProxy = AnchorRunspaceProxy.CreateRunspaceForDatacenterAdmin(this.Context, "upgradehandlers"))
     {
         PSCommand pscommand = new PSCommand();
         pscommand.AddCommand("Set-Mailbox");
         pscommand.AddParameter("Identity", identity);
         pscommand.AddParameter("Arbitration");
         pscommand.AddParameter("Force");
         pscommand.AddParameter("TenantUpgrade", tenantUpgradeCapabilityEnabled);
         try
         {
             anchorRunspaceProxy.RunPSCommand <Mailbox>(pscommand);
         }
         catch (MigrationPermanentException ex)
         {
             this.Context.Logger.Log(MigrationEventType.Error, "Unable to set TenantUpgrade capability for '{0}': {1}", new object[]
             {
                 identity,
                 ex
             });
             throw;
         }
     }
 }
        RecipientWrapper IOrganizationOperation.GetUser(string organizationId, string userId)
        {
            RecipientWrapper result;

            using (AnchorRunspaceProxy anchorRunspaceProxy = AnchorRunspaceProxy.CreateRunspaceForDatacenterAdmin(this.Context, "upgradehandlers"))
            {
                PSCommand pscommand = new PSCommand();
                pscommand.AddCommand("Get-User");
                pscommand.AddParameter("Organization", organizationId);
                pscommand.AddParameter("Identity", userId);
                User user;
                try
                {
                    user = anchorRunspaceProxy.RunPSCommandSingleOrDefault <User>(pscommand);
                }
                catch (Exception ex)
                {
                    this.Context.Logger.Log(MigrationEventType.Error, "MigrationPermanentException from GetUser '{0}'.{1}", new object[]
                    {
                        userId,
                        ex
                    });
                    if (ex.InnerException is ManagementObjectNotFoundException)
                    {
                        throw new UserNotFoundException(userId, ex.InnerException);
                    }
                    throw;
                }
                result = new RecipientWrapper(user);
            }
            return(result);
        }
        public async Task <List <PSCommandMessage> > Handle(GetCommandParams request, CancellationToken cancellationToken)
        {
            PSCommand psCommand = new PSCommand();

            // Executes the following:
            // Get-Command -CommandType Function,Cmdlet,ExternalScript | Sort-Object -Property Name
            psCommand
            .AddCommand("Microsoft.PowerShell.Core\\Get-Command")
            .AddParameter("CommandType", new[] { "Function", "Cmdlet", "ExternalScript" })
            .AddCommand("Microsoft.PowerShell.Utility\\Sort-Object")
            .AddParameter("Property", "Name");

            IEnumerable <CommandInfo> result = await _powerShellContextService.ExecuteCommandAsync <CommandInfo>(psCommand).ConfigureAwait(false);

            var commandList = new List <PSCommandMessage>();

            if (result != null)
            {
                foreach (CommandInfo command in result)
                {
                    // Some info objects have a quicker way to get the DefaultParameterSet. These
                    // are also the most likely to show up so win-win.
                    string defaultParameterSet = null;
                    switch (command)
                    {
                    case CmdletInfo info:
                        defaultParameterSet = info.DefaultParameterSet;
                        break;

                    case FunctionInfo info:
                        defaultParameterSet = info.DefaultParameterSet;
                        break;
                    }

                    if (defaultParameterSet == null)
                    {
                        // Try to get the default ParameterSet if it isn't streamlined (ExternalScriptInfo for example)
                        foreach (CommandParameterSetInfo parameterSetInfo in command.ParameterSets)
                        {
                            if (parameterSetInfo.IsDefault)
                            {
                                defaultParameterSet = parameterSetInfo.Name;
                                break;
                            }
                        }
                    }

                    commandList.Add(new PSCommandMessage
                    {
                        Name                = command.Name,
                        ModuleName          = command.ModuleName,
                        Parameters          = command.Parameters,
                        ParameterSets       = command.ParameterSets,
                        DefaultParameterSet = defaultParameterSet
                    });
                }
            }

            return(commandList);
        }
Example #18
0
        private async Task <VariableContainerDetails> FetchVariableContainer(
            string scope,
            VariableContainerDetails autoVariables)
        {
            PSCommand psCommand = new PSCommand();

            psCommand.AddCommand("Get-Variable");
            psCommand.AddParameter("Scope", scope);

            var scopeVariableContainer =
                new VariableContainerDetails("Scope: " + scope);

            _variables.Add(scopeVariableContainer);

            var results = await ExecuteCommand <PSVariable>(psCommand);

            if (results != null)
            {
                foreach (PSVariable psvariable in results)
                {
                    var variableDetails = new VariableDetails(psvariable); // { Id = this.nextVariableId++ };
                    _variables.Add(variableDetails);
                    scopeVariableContainer.Children.Add(variableDetails);  //.Add(variableDetails.Name, variableDetails);

                    if ((autoVariables != null) && AddToAutoVariables(psvariable, scope))
                    {
                        autoVariables.Children.Add(variableDetails); //(variableDetails.Name, variableDetails);
                    }
                }
            }

            return(scopeVariableContainer);
        }
Example #19
0
        /// <summary>
        /// Creates a new file or project from a specified template and
        /// places it in the destination path.  This ultimately calls
        /// Invoke-Plaster in PowerShell.
        /// </summary>
        /// <param name="templatePath">The folder path containing the template.</param>
        /// <param name="destinationPath">The folder path where the files will be created.</param>
        /// <returns>A boolean-returning Task which communicates success or failure.</returns>
        public async Task <bool> CreateFromTemplate(
            string templatePath,
            string destinationPath)
        {
            this.logger.Write(
                LogLevel.Verbose,
                $"Invoking Plaster...\n\n    TemplatePath: {templatePath}\n    DestinationPath: {destinationPath}");

            PSCommand command = new PSCommand();

            command.AddCommand("Invoke-Plaster");
            command.AddParameter("TemplatePath", templatePath);
            command.AddParameter("DestinationPath", destinationPath);

            var errorString = new System.Text.StringBuilder();

            await this.powerShellContext.ExecuteCommand <PSObject>(
                command,
                errorString,
                new ExecutionOptions
            {
                WriteOutputToHost      = false,
                WriteErrorsToHost      = true,
                InterruptCommandPrompt = true
            });

            // If any errors were written out, creation was not successful
            return(errorString.Length == 0);
        }
        // Token: 0x06000E77 RID: 3703 RVA: 0x00057014 File Offset: 0x00055214
        public Collection <PSObject> RunPowershellScript(string scriptFile, Dictionary <string, string> scriptParameters, out Collection <ErrorRecord> errors, IPublicFolderMailboxLoggerBase logger)
        {
            errors = null;
            Command command = new Command(scriptFile, false);

            if (scriptParameters != null)
            {
                foreach (KeyValuePair <string, string> keyValuePair in scriptParameters)
                {
                    CommandParameter item;
                    if (keyValuePair.Value.ToString().Contains("SwitchValue"))
                    {
                        item = new CommandParameter(keyValuePair.Key, new SwitchParameter(true));
                    }
                    else
                    {
                        item = new CommandParameter(keyValuePair.Key, keyValuePair.Value);
                    }
                    command.Parameters.Add(item);
                }
            }
            PSCommand pscommand = new PSCommand();

            pscommand.AddCommand(command);
            return(this.RunPSCommand <PSObject>(pscommand, out errors, logger));
        }
        protected PowerShellResults <O> GetObject <O>(string getCmdlet)
        {
            PSCommand pscommand = new PSCommand();

            pscommand.AddCommand(getCmdlet);
            return(this.GetObject <O>(pscommand));
        }
Example #22
0
        static void Main(string[] args)
        {
            string    uname     = Console.ReadLine();
            string    pwd       = Console.ReadLine();
            PSCommand psCommand = new PSCommand();

            psCommand.AddScript("$PSHome");
            PowerShell ps = PowerShell.Create();

            ps.Commands = psCommand;

            Collection <PSObject> results = ps.Invoke();

            Console.WriteLine("results length::" + results.Count);

            foreach (PSObject res in results)
            {
                Console.WriteLine("Res val::" + res.ToString());
            }

            Runspace runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();
            ps.Runspace = runspace;

            results = ps.Invoke();
            Console.WriteLine("results length::" + results.Count);

            foreach (PSObject res in results)
            {
                Console.WriteLine("Res val::" + res.ToString());
            }

            PSCommand rmcommand   = new PSCommand();
            string    exchangeUri = "https://outlook.office365.com/powershell-liveid/";
            Uri       uri         = new Uri(exchangeUri);

            rmcommand.AddCommand("New-PSSession");
            rmcommand.AddParameter("ConfigurationName", "Microsoft.Exchange");
            rmcommand.AddParameter("ConnectionUri", uri);

            SecureString password = new SecureString();

            foreach (char c in pwd)
            {
                password.AppendChar(c);
            }

            PSCredential creds = new PSCredential(uname, password);

            rmcommand.AddParameter("Credential", creds);
            rmcommand.AddParameter("Authentication", "Basic");
            rmcommand.AddParameter("AllowRedirection");

            ps.Commands = rmcommand;

            Collection <PSObject> result = ps.Invoke();

            Console.ReadLine();
        }
        public void Should_ThrowOnUnknownHostEntry()
        {
            _powerShell.Commands.Clear();
            var mySM = new MockServiceManager();

            ServiceManager.Provider = () => mySM;

            var hfe = new HostFileEntry()
            {
                Address  = "127.0.0.2",
                Hostname = "abc.com"
            };

            mySM.SetupExistingHostList(new[] { hfe });

            PSCommand psCmd = new PSCommand();

            psCmd.AddCommand("Set-HfHostAddress");
            psCmd.AddParameter("Hostname", hfe.Hostname + "aa");
            psCmd.AddParameter("Address", hfe.Hostname + "11.11.11.11");

            try
            {
                _powerShell.Commands = psCmd;
                _powerShell.Invoke();
            }
            catch (CmdletInvocationException cex)
            {
                throw cex.InnerException ?? cex;
            }

            // END FUNCTION
        }
Example #24
0
        public static void RemoveAllFolderPermissions(string mailbox, string folder)
        {
            PSCommand commands = new PSCommand();

            if (folder == "\\Top of Information Store")
            {
                folder = "\\";
            }
            string                folderPath         = mailbox + ":" + folder;
            SwitchParameter       noConfirm          = new SwitchParameter();
            Collection <PSObject> currentPermissions = GetFolderPermissions(mailbox, folder);

            foreach (PSObject permission in currentPermissions)
            {
                if (permission.Properties["User"].Value.ToString() != "Default" && permission.Properties["User"].Value.ToString() != "Anonymous")
                {
                    commands.Clear();
                    commands.AddCommand("Remove-MailboxFolderPermission");
                    commands.AddParameter("Identity", folderPath);
                    commands.AddParameter("User", permission.Properties["User"].Value.ToString());
                    commands.AddParameter("Confirm", noConfirm);
                    runPowershellCommands(commands);
                }
            }
        }
Example #25
0
        /// <summary>
        /// Gets the available file or project templates on the user's
        /// machine.
        /// </summary>
        /// <param name="includeInstalledModules">
        /// If true, searches the user's installed PowerShell modules for
        /// included templates.
        /// </param>
        /// <returns>A Task which can be awaited for the TemplateDetails list to be returned.</returns>
        public async Task <TemplateDetails[]> GetAvailableTemplates(
            bool includeInstalledModules)
        {
            if (!this.isPlasterLoaded)
            {
                throw new InvalidOperationException("Plaster is not loaded, templates cannot be accessed.");
            }
            ;

            PSCommand psCommand = new PSCommand();

            psCommand.AddCommand("Get-PlasterTemplate");

            if (includeInstalledModules)
            {
                psCommand.AddParameter("IncludeModules");
            }

            var templateObjects =
                await this.powerShellContext.ExecuteCommand <PSObject>(
                    psCommand, false, false);

            this.logger.Write(
                LogLevel.Verbose,
                $"Found {templateObjects.Count()} Plaster templates");

            return
                (templateObjects
                 .Select(CreateTemplateDetails)
                 .ToArray());
        }
        TenantOrganizationPresentationObjectWrapper IOrganizationOperation.GetOrganization(string tenantId)
        {
            TenantOrganizationPresentationObjectWrapper result;

            using (AnchorRunspaceProxy anchorRunspaceProxy = AnchorRunspaceProxy.CreateRunspaceForDatacenterAdmin(this.Context, "upgradehandlers"))
            {
                PSCommand pscommand = new PSCommand();
                pscommand.AddCommand("Get-Organization");
                pscommand.AddParameter("Identity", tenantId);
                TenantOrganizationPresentationObject tenant = null;
                try
                {
                    tenant = anchorRunspaceProxy.RunPSCommandSingleOrDefault <TenantOrganizationPresentationObject>(pscommand);
                }
                catch (Exception ex)
                {
                    this.Context.Logger.Log(MigrationEventType.Error, "MigrationPermanentException from GetOrganization '{0}'.{1}", new object[]
                    {
                        tenantId,
                        ex
                    });
                    if (ex.InnerException is ManagementObjectNotFoundException)
                    {
                        throw new OrganizationNotFoundException(tenantId, ex);
                    }
                    throw;
                }
                result = new TenantOrganizationPresentationObjectWrapper(tenant);
            }
            return(result);
        }
        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;
            }
        }
        /// <summary>
        /// Sets the list of breakpoints for the current debugging session.
        /// </summary>
        /// <param name="scriptFile">The ScriptFile in which breakpoints will be set.</param>
        /// <param name="lineNumbers">The line numbers at which breakpoints will be set.</param>
        /// <param name="clearExisting">If true, causes all existing breakpoints to be cleared before setting new ones.</param>
        /// <returns>An awaitable Task that will provide details about the breakpoints that were set.</returns>
        public async Task <BreakpointDetails[]> SetBreakpoints(
            ScriptFile scriptFile,
            int[] lineNumbers,
            bool clearExisting = true)
        {
            IEnumerable <Breakpoint> resultBreakpoints = null;

            if (clearExisting)
            {
                await this.ClearBreakpointsInFile(scriptFile);
            }

            if (lineNumbers.Length > 0)
            {
                PSCommand psCommand = new PSCommand();
                psCommand.AddCommand("Set-PSBreakpoint");
                psCommand.AddParameter("Script", scriptFile.FilePath);
                psCommand.AddParameter("Line", lineNumbers.Length > 0 ? lineNumbers : null);

                resultBreakpoints =
                    await this.powerShellContext.ExecuteCommand <Breakpoint>(
                        psCommand);

                return
                    (resultBreakpoints
                     .Select(BreakpointDetails.Create)
                     .ToArray());
            }

            return(new BreakpointDetails[0]);
        }
Example #29
0
        /// <summary>
        /// Gets an array of commands that can be run sequentially to set $profile and run the profile commands.
        /// </summary>
        /// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
        /// <param name="useTestProfile">used from test not to overwrite the profile file names from development boxes</param>
        /// <returns>An array of commands.</returns>
        internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile)
        {
            List <PSCommand> commands               = new List <PSCommand>();
            string           allUsersAllHosts       = HostUtilities.GetFullProfileFileName(null, false, useTestProfile);
            string           allUsersCurrentHost    = HostUtilities.GetFullProfileFileName(shellId, false, useTestProfile);
            string           currentUserAllHosts    = HostUtilities.GetFullProfileFileName(null, true, useTestProfile);
            string           currentUserCurrentHost = HostUtilities.GetFullProfileFileName(shellId, true, useTestProfile);
            PSObject         dollarProfile          = HostUtilities.GetDollarProfile(allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost);
            PSCommand        command = new PSCommand();

            command.AddCommand("set-variable");
            command.AddParameter("Name", "profile");
            command.AddParameter("Value", dollarProfile);
            command.AddParameter("Option", ScopedItemOptions.None);
            commands.Add(command);

            string[] profilePaths = new string[] { allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost };
            foreach (string profilePath in profilePaths)
            {
                if (!System.IO.File.Exists(profilePath))
                {
                    continue;
                }

                command = new PSCommand();
                command.AddCommand(profilePath, false);
                commands.Add(command);
            }

            return(commands.ToArray());
        }
Example #30
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);
        }
Example #31
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;
        }