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 #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);
        }
        public PowerShellResults <MailboxSearchRow> StartSearch(Identity[] identities, StartMailboxSearchParameters parameters)
        {
            List <Identity> list = new List <Identity>();

            if (parameters != null && parameters.Resume)
            {
                list.AddRange(identities);
            }
            else
            {
                foreach (Identity identity in identities)
                {
                    PowerShellResults <MailboxSearch> @object = base.GetObject <MailboxSearch>("Get-MailboxSearch", identity);
                    if (@object.Succeeded && @object.HasValue)
                    {
                        if ([email protected][0].IsEstimateOnly)
                        {
                            PSCommand pscommand = new PSCommand().AddCommand("Set-MailboxSearch");
                            pscommand.AddParameter("Identity", identity);
                            pscommand.AddParameter("EstimateOnly", true);
                            pscommand.AddParameter("ExcludeDuplicateMessages", false);
                            pscommand.AddParameter("LogLevel", LoggingLevel.Suppress);
                            pscommand.AddParameter("Force", true);
                            PowerShellResults powerShellResults = base.Invoke(pscommand);
                            if (!powerShellResults.Succeeded)
                            {
                                break;
                            }
                        }
                        list.Add(identity);
                    }
                }
            }
            return(base.InvokeAndGetObject <MailboxSearchRow>(new PSCommand().AddCommand("Start-MailboxSearch"), list.ToArray(), parameters));
        }
        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 #5
0
 // Token: 0x0600003D RID: 61 RVA: 0x00002F64 File Offset: 0x00001164
 protected virtual void CreateMigrationBatch(MailboxId migrationMailbox, byte[] csvFile)
 {
     for (int i = 0; i < 3; i++)
     {
         try
         {
             using (AnchorRunspaceProxy anchorRunspaceProxy = AnchorRunspaceProxy.CreateRunspaceForDatacenterAdmin(base.Context, base.Context.ApplicationName))
             {
                 PSCommand pscommand = new PSCommand();
                 pscommand.AddCommand("New-MigrationBatch");
                 pscommand.AddParameter("XO1", true);
                 pscommand.AddParameter("CSVData", csvFile);
                 pscommand.AddParameter("Partition", migrationMailbox);
                 anchorRunspaceProxy.RunPSCommand <PSObject>(pscommand);
             }
             base.Context.Logger.Log(MigrationEventType.Information, "Successfully created new migration batch against {0}", new object[]
             {
                 migrationMailbox
             });
             break;
         }
         catch (InvalidRunspaceStateException ex)
         {
             base.Context.Logger.Log(MigrationEventType.Error, "PS Runspace was closed so command could not be run : {0}", new object[]
             {
                 ex
             });
         }
     }
 }
Example #6
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);
        }
 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;
         }
     }
 }
        // Отключение ActiveSync и WebApp у пользователя
        private void DisableActiveSyncWebAppPS(string userLogin, string mailServerAdr, string login, SecureString password, ref string errorMsg)
        {
            PSCredential        credential     = new PSCredential(login, password);
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(mailServerAdr)), "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();

            command.AddCommand("Set-CASMailbox");
            command.AddParameter("Identity", userLogin);
            command.AddParameter("ActiveSyncEnabled", false);
            command.AddParameter("OWAEnabled", false);

            powershell.Commands = command;
            try
            {
                runspace.Open();
                powershell.Runspace = runspace;
                powershell.Invoke();
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
            }
            finally
            {
                runspace.Dispose();
                runspace = null;
                powershell.Dispose();
                powershell = null;
            }
        }
Example #9
0
        /// <summary>
        /// This method removes an existing AD group
        /// </summary>
        /// <param name="group_identity"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel RemoveADGroup(string group_identity)
        {
            UtilityController util = new UtilityController();

            try
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Remove-ADGroup");
                    command.AddParameter("identity", group_identity);
                    command.AddParameter("confirm", false);
                    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)
            {
                if (!e.Message.Contains(cantFindObjectError))
                {
                    return(util.ReportError(e));
                }
                return(util.ReportHiddenError(e));
            }
        }
        /// <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]);
        }
        /// <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)
            {
                // Fix for issue #123 - file paths that contain wildcard chars [ and ] need to
                // quoted and have those wildcard chars escaped.
                string escapedScriptPath = PowerShellContext.EscapeWildcardsInPath(scriptFile.FilePath);

                PSCommand psCommand = new PSCommand();
                psCommand.AddCommand("Set-PSBreakpoint");
                psCommand.AddParameter("Script", escapedScriptPath);
                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 #12
0
        public PowerShellResults <NewUMMailboxConfiguration> GetConfigurationForNewUMMailbox(Identity identity, UMEnableSelectedPolicyParameters properties)
        {
            properties.FaultIfNull();
            PSCommand pscommand = new PSCommand().AddCommand("Enable-UMMailbox");

            pscommand.AddParameter("Identity", identity);
            pscommand.AddParameter("ValidateOnly");
            if (properties.UMMailboxPolicy != null)
            {
                pscommand.AddParameter("UMMailboxPolicy", properties.UMMailboxPolicy);
            }
            PowerShellResults <NewUMMailboxConfiguration> powerShellResults = base.Invoke <NewUMMailboxConfiguration>(pscommand);

            if (!powerShellResults.Succeeded)
            {
                powerShellResults.ErrorRecords = Array.FindAll <ErrorRecord>(powerShellResults.ErrorRecords, (ErrorRecord x) => !(x.Exception is CouldNotGenerateExtensionException) && !(x.Exception is SipResourceIdAndExtensionsNeededException) && !(x.Exception is E164ResourceIdNeededException));
            }
            if (powerShellResults.SucceededWithValue)
            {
                PowerShellResults <UMMailboxPolicy> powerShellResults2 = powerShellResults.MergeErrors <UMMailboxPolicy>(base.GetObject <UMMailboxPolicy>("Get-UMMailboxPolicy", properties.UMMailboxPolicy));
                if (powerShellResults2.SucceededWithValue)
                {
                    powerShellResults.Value.Policy = powerShellResults2.Value;
                }
            }
            return(powerShellResults);
        }
        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);
        }
Example #14
0
        public bool StartCode(string login, string password) /// Check if the credentials are valid
        {
            string connectionUri = "https://outlook.office365.com/powershell-liveid/";
            // string connectionUri = "https://ps.outlook.com/powershell/";
            SecureString secpassword = new SecureString();

            foreach (char c in password)
            {
                secpassword.AppendChar(c);
            }
            PSCredential credential = new PSCredential(login, secpassword);

            runspace = RunspaceFactory.CreateRunspace();
            command  = new PSCommand(); command.AddCommand("New-PSSession");
            command.AddParameter("ConfigurationName", "Microsoft.Exchange");
            command.AddParameter("ConnectionUri", new Uri(connectionUri));
            command.AddParameter("Credential", credential);
            command.AddParameter("Authentication", "Basic");
            powershell.Commands = command; runspace.Open();
            powershell.Runspace = runspace; result = powershell.Invoke();
            if (powershell.Streams.Error.Count > 0 || result.Count != 1)
            {
                return(false);
            }
            CredsAreValid = true;
            return(true);
        }
Example #15
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 #16
0
        /// <summary>
        /// Uses _savedCredential in order to enter into a remote session with a remote machine. If _savedCredential is null, method will instead
        /// use InvokeScript to prompt/enter into a session without saving credentials.
        /// </summary>
        /// <param name="powerShell">This should be an already instanstiated PowerShell object, and should be inside of a using. If
        /// powerShell is null, method will return without performing any action.</param>
        /// <param name="remoteName">Machine to connect to.</param>
        private void EnterCredentialedRemoteSession(PowerShell powerShell, string remoteName, int port, bool useSSL)
        {
            if (powerShell == null)
            {
                // callee is expected to passs in an already inalized PowerShell object to this method
                return;
            }

            if (_savedCredential == null)
            {
                InvokeScript(powerShell, string.Format(DebugEngineConstants.EnterRemoteSessionDefaultCommand, remoteName));
                return;
            }

            PSCommand enterSession = new PSCommand();

            enterSession.AddCommand("Enter-PSSession").AddParameter("ComputerName", remoteName).AddParameter("Credential", _savedCredential);

            if (port != -1)
            {
                // check for user specified port
                enterSession.AddParameter("-Port", port);
            }
            if (useSSL)
            {
                // if told to use SSL from options dialog, add the SSL parameter
                enterSession.AddParameter("-UseSSL");
            }

            powerShell.Runspace = _runspace;
            powerShell.Commands.Clear();
            powerShell.Commands = enterSession;
            powerShell.Invoke();
        }
Example #17
0
        public PowerShellResults <DeviceAccessRuleRow> NewObject(NewDeviceAccessRule properties)
        {
            if (properties.DeviceTypeQueryString == null)
            {
                throw new FaultException(Strings.DeviceTypeRequired);
            }
            if (properties.DeviceModelQueryString == null)
            {
                throw new FaultException(Strings.DeviceModelRequired);
            }
            PSCommand pscommand = new PSCommand().AddCommand("New-ActiveSyncDeviceAccessRule").AddParameters(properties);

            if (!properties.DeviceTypeQueryString.IsWildcard && properties.DeviceModelQueryString.IsWildcard)
            {
                pscommand.AddParameter(ActiveSyncDeviceAccessRuleSchema.Characteristic.Name, DeviceAccessCharacteristic.DeviceType);
                pscommand.AddParameter(ActiveSyncDeviceAccessRuleSchema.QueryString.Name, properties.DeviceTypeQueryString.QueryString);
            }
            else
            {
                if (!properties.DeviceTypeQueryString.IsWildcard || properties.DeviceModelQueryString.IsWildcard)
                {
                    throw new FaultException(Strings.InvalidDeviceAccessCharacteristic);
                }
                pscommand.AddParameter(ActiveSyncDeviceAccessRuleSchema.Characteristic.Name, DeviceAccessCharacteristic.DeviceModel);
                pscommand.AddParameter(ActiveSyncDeviceAccessRuleSchema.QueryString.Name, properties.DeviceModelQueryString.QueryString);
            }
            return(base.Invoke <DeviceAccessRuleRow>(pscommand));
        }
Example #18
0
        /// <summary>
        /// Add user to an AD group
        /// </summary>
        /// <param name="group_identity"></param>
        /// <param name="group_member"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel AddADGroupMember(string group_identity, string group_member)
        {
            try
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Add-ADGroupMember");
                    command.AddParameter("identity", group_identity);
                    command.AddParameter("member", group_member);
                    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));
            }
        }
Example #19
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();
        }
Example #20
0
        /// <summary>
        /// Analyze a given script using PSScriptAnalyzer.
        /// </summary>
        /// <param name="scriptContent">The contents of the script to analyze.</param>
        /// <param name="settings">The settings file to use in this instance of analysis.</param>
        /// <returns>An array of markers indicating script analysis diagnostics.</returns>
        public Task <ScriptFileMarker[]> AnalyzeScriptAsync(string scriptContent, Hashtable settings)
        {
            // When a new, empty file is created there are by definition no issues.
            // Furthermore, if you call Invoke-ScriptAnalyzer with an empty ScriptDefinition
            // it will generate a ParameterBindingValidationException.
            if (string.IsNullOrEmpty(scriptContent))
            {
                return(Task.FromResult(Array.Empty <ScriptFileMarker>()));
            }

            var command = new PSCommand()
                          .AddCommand("Invoke-ScriptAnalyzer")
                          .AddParameter("ScriptDefinition", scriptContent)
                          .AddParameter("Severity", s_scriptMarkerLevels);

            object settingsValue = settings ?? _settingsParameter;

            if (settingsValue != null)
            {
                command.AddParameter("Settings", settingsValue);
            }
            else
            {
                command.AddParameter("IncludeRule", _rulesToInclude);
            }

            return(GetSemanticMarkersFromCommandAsync(command));
        }
 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;
         }
     }
 }
Example #22
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 #23
0
        /// <summary>
        /// This method changes the surname of a user in AD.
        /// </summary>
        /// <param name="employeeid"></param>
        /// <param name="samaccountname"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel ChangeUserValueDriver(string employeeid, string samaccountname, string field, string value)
        {
            try
            {
                if (value == "")
                {
                    value = null;
                }
                string   dName;
                PSObject user = util.getADUser(employeeid, samaccountname);
                if (user == null)
                {
                    throw new Exception("User was not found.");
                }
                dName = user.Properties["DistinguishedName"].Value.ToString();
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Set-ADUser");
                    command.AddParameter("Identity", dName);
                    if (field.ToLower() == "ipphone")
                    {
                        if (value != null)
                        {
                            Hashtable attrHash = new Hashtable
                            {
                                { field, value }
                            };
                            command.AddParameter("replace", attrHash);
                        }
                        else
                        {
                            String[] attrArray = new String[1];
                            attrArray[0] = field;
                            command.AddParameter("clear", attrArray);
                        }
                    }
                    else
                    {
                        command.AddParameter(field, value);
                    }
                    command.AddParameter("ErrorVariable", "Err");
                    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));
            }
        }
        public PowerShellResults ResetPIN(Identity identity)
        {
            PSCommand pscommand = new PSCommand().AddCommand("Set-UMMailboxPIN");

            pscommand.AddParameter("Identity", Identity.FromExecutingUserId());
            pscommand.AddParameter("PinExpired", true);
            return(base.Invoke(pscommand));
        }
Example #25
0
        public PowerShellResults <InboxRule> GetObject(Identity identity)
        {
            PSCommand pscommand = new PSCommand().AddCommand("Get-InboxRule");

            pscommand.AddParameter("DescriptionTimeFormat", EcpDateTimeHelper.GetWeekdayDateFormat(true));
            pscommand.AddParameter("DescriptionTimeZone", RbacPrincipal.Current.UserTimeZone);
            return(base.GetObject <InboxRule>(pscommand, identity));
        }
Example #26
0
        public PowerShellResults StartLogging(Identity[] identities, BaseWebServiceParameters parameters)
        {
            PSCommand pscommand = new PSCommand().AddCommand("Set-CASMailbox");

            pscommand.AddParameter("Identity", Identity.FromExecutingUserId());
            pscommand.AddParameter("ActiveSyncDebugLogging", true);
            return(base.Invoke(pscommand));
        }
Example #27
0
        private PowerShellResults ComparePasscode(Identity identity, string passcode)
        {
            PSCommand pscommand = new PSCommand().AddCommand("Compare-TextMessagingVerificationCode");

            pscommand.AddParameter("Identity", identity);
            pscommand.AddParameter("VerificationCode", passcode);
            return(base.Invoke(pscommand));
        }
Example #28
0
        /// <summary>
        /// Sample execution scenario 2: Asynchronous
        /// </summary>
        /// <remarks>
        /// Executes a PowerShell script asynchronously with script output and event handling.
        /// </remarks>
        static void ExecuteAsynchronously()
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                // this script has a sleep in it to simulate a long running script
                //PowerShellInstance.AddScript("$s1 = 'test1'; $s2 = 'test2'; $s1; write-error 'some error';start-sleep -s 7; $s2");

                //PowerShellInstance.AddScript("Invoke-Command");

                //PowerShellInstance.AddParameter("ScriptBlock", "test.ps1");

                PowerShellInstance.AddScript("Set-ExecutionPolicy");
                PowerShellInstance.AddParameter("ExecutionPolicy", "ByPass");

                PowerShellInstance.Invoke();

                PSCommand cmd         = new PSCommand();
                String    machinename = "localhost";
                String    file        = AppDomain.CurrentDomain.BaseDirectory + "\\test.ps1";
                cmd.AddCommand("Invoke-Command");
                cmd.AddParameter("ComputerName", machinename);
                //cmd.AddParameter("FilePath", file);
                cmd.AddParameter("ScriptBlock", ScriptBlock.Create(file));

                PowerShellInstance.Commands = cmd;

                // prepare a new collection to store output stream objects
                PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();
                outputCollection.DataAdded += outputCollection_DataAdded;

                // the streams (Error, Debug, Progress, etc) are available on the PowerShell instance.
                // we can review them during or after execution.
                // we can also be notified when a new item is written to the stream (like this):
                PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded;

                // begin invoke execution on the pipeline
                // use this overload to specify an output stream buffer
                IAsyncResult result = PowerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection);

                // do something else until execution has completed.
                // this could be sleep/wait, or perhaps some other work
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Waiting for pipeline to finish...");
                    Thread.Sleep(1000);

                    // might want to place a timeout here...
                }

                Console.WriteLine("Execution has stopped. The pipeline state: " + PowerShellInstance.InvocationStateInfo.State);

                foreach (PSObject outputItem in outputCollection)
                {
                    //TODO: handle/process the output items if required
                    Console.WriteLine(outputItem.BaseObject.ToString());
                }
            }
        }
Example #29
0
        public static Collection <PSObject> GetMailboxes()
        {
            PSCommand commands = new PSCommand();

            commands.AddCommand("Get-Mailbox");
            commands.AddParameter("RecipientTypeDetails", "UserMailbox");
            commands.AddParameter("SortBy", "Name");
            return(runPowershellCommands(commands));
        }
Example #30
0
        public static Collection <PSObject> GetGroups()
        {
            PSCommand commands = new PSCommand();

            commands.AddCommand("Get-Group");
            commands.AddParameter("RecipientTypeDetails", "MailUniversalSecurityGroup");
            commands.AddParameter("SortBy", "Name");
            return(runPowershellCommands(commands));
        }