예제 #1
1
        public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();

            if (connect)
            {
                var pipeLine = _runSpace.CreatePipeline();
                Command cmd = new Command("connect-sponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
예제 #2
0
파일: Utils.cs 프로젝트: mrhovnet/WinCertes
        /// <summary>
        /// Executes powershell script scriptFile
        /// </summary>
        /// <param name="scriptFile"></param>
        /// <param name="pfx"></param>
        /// <param name="pfxPassword"></param>
        /// <returns></returns>
        public static bool ExecutePowerShell(string scriptFile, AuthenticatedPFX pfx)
        {
            if (scriptFile == null)
            {
                return(false);
            }
            try {
                // First let's create the execution runspace
                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
                runspace.Open();

                // Now we create the pipeline
                Pipeline pipeline = runspace.CreatePipeline();

                // We create the script to execute with its arguments as a Command
                System.Management.Automation.Runspaces.Command myCommand = new System.Management.Automation.Runspaces.Command(scriptFile);
                CommandParameter pfxParam = new CommandParameter("pfx", pfx.PfxFullPath);
                myCommand.Parameters.Add(pfxParam);
                CommandParameter pfxPassParam = new CommandParameter("pfxPassword", pfx.PfxPassword);
                myCommand.Parameters.Add(pfxPassParam);

                // add the created Command to the pipeline
                pipeline.Commands.Add(myCommand);

                // and we invoke it
                var results = pipeline.Invoke();
                logger.Info($"Executed script {scriptFile}.");
                return(true);
            } catch (Exception e) {
                logger.Error($"Could not execute {scriptFile}: {e.Message}");
                return(false);
            }
        }
예제 #3
0
        protected override Command BuildCommand()
        {
            var result = new Command(CommandName);

            if (String.IsNullOrWhiteSpace(Location) == false)
            {
                result.Parameters.Add(LocationParameter, Location);
            }

            if (String.IsNullOrWhiteSpace(ServiceName) == false)
            {
                result.Parameters.Add(ServiceNameParameter, ServiceName);
            }

            if (String.IsNullOrWhiteSpace(DeploymentName) == false)
            {
                result.Parameters.Add(DeploymentNameParameter, DeploymentName);
            }

            if (WaitForBoot)
            {
                result.Parameters.Add(WaitForBootParameter);
            }

            return result;
        }
예제 #4
0
        public static void SetFirewallRule(PowerShellManager powerShell, bool enabled)
        {
            Command cmd = new Command("Enable-Netfirewallrule");
            cmd.Parameters.Add("DisplayName", "Hyper-V Replica HTTPS Listener (TCP-In)");

            powerShell.Execute(cmd, false);
        }
예제 #5
0
        internal override void Execute(Pash.Implementation.ExecutionContext context, ICommandRuntime commandRuntime)
        {
            ExecutionContext nestedContext = context.CreateNestedContext();

            if (! (context.CurrentRunspace is LocalRunspace))
                throw new InvalidOperationException("Invalid context");

            // MUST: fix this with the commandRuntime
            Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline();
            context.PushPipeline(pipeline);

            try
            {
                Command cmd = new Command("Get-Variable");
                cmd.Parameters.Add("Name", new string[] { Text });
                // TODO: implement command invoke
                pipeline.Commands.Add(cmd);

                commandRuntime.WriteObject(pipeline.Invoke(), true);
                //context.outputStreamWriter.Write(pipeline.Invoke(), true);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                context.PopPipeline();
            }
        }
        public void InitializeTests()
        {

            RunspaceConfiguration config = RunspaceConfiguration.Create();
            
            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();

            // do login first to start tests
            using (Pipeline pipeline = runspace.CreatePipeline())
            {

                Command command = new Command("Get-SfClient");
                command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));

                pipeline.Commands.Add(command);

                Collection<PSObject> objs = pipeline.Invoke();
                Assert.AreEqual<int>(1, objs.Count);
                sfLogin = objs[0];
            }
        }
예제 #7
0
 public override void SetVariable(string name, object value)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     if (this.setVariableCommandNotFoundException != null)
     {
         throw this.setVariableCommandNotFoundException;
     }
     Pipeline pipeline = this._runspace.CreatePipeline();
     Command item = new Command(@"Microsoft.PowerShell.Utility\Set-Variable");
     item.Parameters.Add("Name", name);
     item.Parameters.Add("Value", value);
     pipeline.Commands.Add(item);
     try
     {
         pipeline.Invoke();
     }
     catch (RemoteException exception)
     {
         if (string.Equals("CommandNotFoundException", exception.ErrorRecord.FullyQualifiedErrorId, StringComparison.OrdinalIgnoreCase))
         {
             this.setVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, exception);
             throw this.setVariableCommandNotFoundException;
         }
         throw;
     }
     if (pipeline.Error.Count > 0)
     {
         ErrorRecord record = (ErrorRecord) pipeline.Error.Read();
         throw new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, record.Exception);
     }
 }
예제 #8
0
        public bool SubscriptionEventNotification(SubscriptionNotification notification)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.ApartmentState = System.Threading.ApartmentState.STA;
            runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;

            runspace.Open();

            Pipeline pipeline = runspace.CreatePipeline();
            var myCmd = new Command( Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "Invoke-Subscriber.ps1" ) );
            myCmd.Parameters.Add( new CommandParameter( "event", notification.NotificationType.ToString() ));
            myCmd.Parameters.Add( new CommandParameter( "href", notification.RelativeHref ));
            myCmd.Parameters.Add( new CommandParameter( "subscriptions", notification.SubscriptionArray ));
            myCmd.Parameters.Add( new CommandParameter( "changes", notification.ChangesArray ));
            pipeline.Commands.Add( myCmd );

            // Execute PowerShell script
            // Instead of implementing our own Host and HostUI we keep this extremely simple by
            // catching everything to cope with HostExceptions and UnknownCommandExceptions etc.
            // The first will be thrown if someone tries to access unsupported (i.e. interactive)
            // host features such as Read-Host and the latter will occur for all unsupported commands.
            // That can easily happen if a script is missing an import-module or just contains a mispelled command
            try
            {
                var result = pipeline.Invoke().FirstOrDefault();
                return result != null && result.BaseObject is bool && (bool)result.BaseObject;
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception caught when invoking powershell script: " + ex);
                return false;
            }
        }
        public ActionResult ExecuteScript(string scriptname, string env, string machine)
        {
            var model = new MachineCommand {Command = scriptname, Result = ""};
            var scriptfilename = Path.Combine(Server.MapPath("~/App_Data/Scripts/"), scriptname);

            using (var runspace = RunspaceFactory.CreateRunspace()) {
                runspace.Open();
                var pipeline = runspace.CreatePipeline();
                var newCommand = new Command(scriptfilename);

                newCommand.Parameters.Add(new CommandParameter("env", env));
                newCommand.Parameters.Add(new CommandParameter("machine", machine));

                pipeline.Commands.Add(newCommand);

                var results = pipeline.Invoke();

                // convert the script result into a single string

                var stringBuilder = new StringBuilder();
                foreach (var obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }

                model.Result = stringBuilder.ToString();
            }

            return View(model);
        }
예제 #10
0
 internal Collection<PSObject> ExecuteCommand(string command, bool isScript, out Exception exceptionThrown, Hashtable args)
 {
     exceptionThrown = null;
     if (this.CancelTabCompletion)
     {
         return new Collection<PSObject>();
     }
     this.CurrentPowerShell.AddCommand(command);
     Command command2 = new Command(command, isScript);
     if (args != null)
     {
         foreach (DictionaryEntry entry in args)
         {
             command2.Parameters.Add((string) entry.Key, entry.Value);
         }
     }
     Collection<PSObject> collection = null;
     try
     {
         if (this.IsStopped)
         {
             collection = new Collection<PSObject>();
             this.CancelTabCompletion = true;
         }
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         exceptionThrown = exception;
     }
     return collection;
 }
예제 #11
0
        internal void CreateSyncShare(string name, string path, string user)
        {
            Log.WriteStart("CreateSyncShare");

            Runspace runSpace = null;

            try
            {
                runSpace = OpenRunspace();

                // ToDo: Add the correct parameters

                Command cmd = new Command("New-SyncShare");
                cmd.Parameters.Add("Name", name);
                cmd.Parameters.Add("Path", path);
                cmd.Parameters.Add("user", user);
                var result = ExecuteShellCommand(runSpace, cmd);

                if (result.Count > 0)
                {

                }
            }
            catch (Exception ex)
            {
                Log.WriteError("CreateSyncShare", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runSpace);
            }

            Log.WriteEnd("CreateSyncShare");
        }
예제 #12
0
        //Called on a WCF worker thread.
        byte[][] ITunnelHost.RunScript(string script, byte[][] pipeInput, bool pipeOutput)
        {
            try
            {
                Collection<PSObject> invokeResult;
                using (Pipeline pipe = Runspace.CreatePipeline(script))
                {
                    if (!pipeOutput)
                    {
                        Command command = new Command("Out-String");
                        command.Parameters.Add("-stream");
                        pipe.Commands.Add(command);
                    }
                    if (pipeInput != null)
                    {
                        foreach (byte[] byteArray in pipeInput)
                            pipe.Input.Write(DeserializeToObject(byteArray), false);
                        pipe.Input.Close();
                    }
                    invokeResult = pipe.Invoke();
                }

                return SerializedPSObjectCollection(invokeResult);
            }
            catch (Exception ex)
            {
                //Prevent the WCF connection from entering the Faulted state.
                throw new FaultException(ex.ToString());
            }
        }
예제 #13
0
        private void RunNested()
        {
            Pipeline pipeline = null;

            try
            {
                pipeline = Runspace.DefaultRunspace.CreateNestedPipeline();
                string script = OSAEScriptManager.GetScriptByName(Name);
                Command psCommand = new Command(script, true);
                pipeline.Commands.Add(psCommand);

                pipeline.Commands.Add("Out-String");

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

                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }

                this.Log.Debug("Script return: \r\n" + stringBuilder.ToString());
            }
            catch (Exception ex)
            {
                this.Log.Error("An error occured while trying to run the script, details", ex);
            }
            finally
            {
                if (pipeline != null)
                {
                    pipeline.Dispose();
                }
            }
        }
예제 #14
0
        public Collection <PSObject> ExecuteRunspace(PCommand.Command paramCommand, string exceptionMsg)
        {
            var results = new Collection <PSObject>();

            try
            {
                //Iterate through each command and execute it.
                foreach (var iteratedCommand in new PCommand.Command[] { connectCommand, paramCommand })
                {
                    var pipe = psRunSpace.CreatePipeline();
                    pipe.Commands.Add(iteratedCommand);

                    // Execute command and generate results and errors (if any).
                    results = pipe.Invoke();
                    var error = pipe.Error.ReadToEnd();

                    if (error.Count > 0 && iteratedCommand == paramCommand)
                    {
                        throw new Exception(exceptionMsg);
                    }
                    else if (results.Count > 0 && iteratedCommand == paramCommand)
                    {
                        return(results);
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO: Implement an appropriate Exception Stack and logging here
                throw new Exception(ex.Message);
            }

            return(results);
        }
예제 #15
0
        internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime)
        {
            ExecutionContext nestedContext = context.CreateNestedContext();

            if (lValue is VariableNode)
            {
                VariableNode varNode = (VariableNode)lValue;

                if (! (context.CurrentRunspace is LocalRunspace))
                    throw new InvalidOperationException("Invalid context");

                // MUST: fix this with the commandRuntime
                Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline();
                context.PushPipeline(pipeline);

                try
                {
                    Command cmd = new Command("Set-Variable");
                    cmd.Parameters.Add("Name", new string[] { varNode.Text });
                    cmd.Parameters.Add("Value", rValue.GetValue(context));
                    // TODO: implement command invoke
                    pipeline.Commands.Add(cmd);
                    pipeline.Invoke();
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    context.PopPipeline();
                }
            }
        }
예제 #16
0
        public static void CreateMail(string userName, string domainName, string dbName)
        {
            using (Pipeline p = CreatePipeline())
            {
                const string psw = "123.com";

                SecureString securePwd = StringToSecureString(psw);
                Command newMailBox = new Command("New-Mailbox");

                newMailBox.Parameters.Add("Name", userName);
                newMailBox.Parameters.Add("Alias", userName);
                newMailBox.Parameters.Add("database", dbName);
                newMailBox.Parameters.Add("Password", securePwd);
                newMailBox.Parameters.Add("DisplayName", userName);
                newMailBox.Parameters.Add("UserPrincipalName", string.Format("{0}@{1}", userName, domainName));
                //newMailBox.Parameters.Add("OrganizationalUnit", "ou=myorg,dc=ad,dc=lab");
                newMailBox.Parameters.Add("FirstName", userName);
                p.Commands.Add(newMailBox);

                try
                {
                    Collection<PSObject> result = p.Invoke();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
예제 #17
0
        public static void Update(PowerShellManager powerShell, VirtualMachine vm, bool bootFromCD, bool numLockEnabled)
        {
            // for Win2012R2+ and Win8.1+
            if (vm.Generation == 2)
            {
                Command cmd = new Command("Set-VMFirmware");

                cmd.Parameters.Add("VMName", vm.Name);
                if (bootFromCD)
                    cmd.Parameters.Add("FirstBootDevice", DvdDriveHelper.GetPS(powerShell, vm.Name));
                else
                    cmd.Parameters.Add("FirstBootDevice", HardDriveHelper.GetPS(powerShell, vm.Name).FirstOrDefault());

                powerShell.Execute(cmd, true);
            }
            // for others win and linux
            else
            {
                Command cmd = new Command("Set-VMBios");

                cmd.Parameters.Add("VMName", vm.Name);
                var bootOrder = bootFromCD
                    ? new[] { "CD", "IDE", "LegacyNetworkAdapter", "Floppy" }
                    : new[] { "IDE", "CD", "LegacyNetworkAdapter", "Floppy" };
                cmd.Parameters.Add("StartupOrder", bootOrder);

                powerShell.Execute(cmd, true);
            }
        }
        public CommandResult RunCommand(ShellCommand command)
        {
            var host = new GoosePSHost();
            var results = new List<string>();
            using (var runspace = RunspaceFactory.CreateRunspace(host))
            {
                var setWorkingDirectory = new Command("set-location");
                setWorkingDirectory.Parameters.Add("path", command.WorkingDirectory);
                var redirectOutput = new Command("out-string");

                runspace.Open();
                var pipeline = runspace.CreatePipeline();
                pipeline.Commands.Add(setWorkingDirectory);
                pipeline.Commands.AddScript(command.Command);
                pipeline.Commands.Add(redirectOutput);

                foreach (var psObject in pipeline.Invoke())
                {
                    var result = FormatCommandResult(psObject);
                    results.Add(result);
                }
                runspace.Close();
            }

            return BuildOutput(results, host);
        }
예제 #19
0
 internal Command ToCommand()
 {
     var command = new Command(CommandName);
     var parameters = GetParameters();
     parameters.ForEach(command.Parameters.Add);
     return command;
 }
        protected override Command BuildCommand()
        {
            var result = new Command(CommandName);

            if (String.IsNullOrWhiteSpace(SrcBlob) == false)
            {
                result.Parameters.Add(SrcBlobParameter, SrcBlob);
            }

            if (String.IsNullOrWhiteSpace(SrcContainer) == false)
            {
                result.Parameters.Add(SrcContainerParameter, SrcContainer);
            }

            if (String.IsNullOrWhiteSpace(DestBlob) == false)
            {
                result.Parameters.Add(DestBlobParameter, DestBlob);
            }

            if (String.IsNullOrWhiteSpace(DestContainer) == false)
            {
                result.Parameters.Add(DestContainerParameter, DestContainer);
            }

            if (Force)
            {
                result.Parameters.Add(ForceParameter);
            }

            return result;
        }
예제 #21
0
        public static StringBuilder ExecuteInlinePowerShellScript(string scriptText, IAgentSettings agentSettings)
        {
            var serviceCommands = new Command(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts/PS/Services.ps1"));

            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it
            runspace.Open();
            var pipeline = runspace.CreatePipeline();
            pipeline.Commands.Add(serviceCommands);

            // add the custom script
            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script output objects into nicely formatted strings
            // remove this line to get the actual objects that the script returns. For example, the script
            // "Get-Process" returns a collection of System.Diagnostics.Process instances.
            pipeline.Commands.Add("Out-String");

            var results = pipeline.Invoke();
            runspace.Close();

            // convert the script result into a single string
            var stringBuilder = new StringBuilder();
            foreach (var obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            return stringBuilder;
        }
        protected override Command BuildCommand()
        {
            var result = new Command(CommandName);

            if (String.IsNullOrWhiteSpace(AdminUsername) == false)
            {
                result.Parameters.Add(AdminUsernameParameter, AdminUsername);
            }

            if (String.IsNullOrWhiteSpace(AdminPassword) == false)
            {
                result.Parameters.Add(PasswordParameter, AdminPassword);
            }

            if (String.IsNullOrWhiteSpace(TimeZone) == false)
            {
                result.Parameters.Add(TimeZoneParameter, TimeZone);
            }

            if (Windows)
            {
                result.Parameters.Add(WindowsParameter);
            }

            return result;
        }
예제 #23
0
        /// <summary>
        ///     Executes a powershell script
        /// </summary>
        /// <param name="folder">Folder where to execute the script</param>
        /// <param name="file">Script to execute</param>
        /// <param name="configuration">Configuration used</param>
        /// <param name="log">Logger to use</param>
        /// <param name="parameters">Parameters for the script</param>
        public static void Execute(string folder, string file, string configuration, ILogger log, Dictionary<string, string> parameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(new Host(), runspaceConfiguration);
            runspace.Open();
            runspace.SessionStateProxy.Path.SetLocation(folder);

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
            Pipeline pipeline = runspace.CreatePipeline();

            Command myCommand = new Command(Path.Combine(folder, file));

            foreach (var param in parameters.Keys)
            {
                myCommand.Parameters.Add(new CommandParameter("-" + param, parameters[param]));
            }

            myCommand.Parameters.Add(new CommandParameter("-Verb", "RunAs"));
            pipeline.Commands.Add(myCommand);

            Collection<PSObject> results = new Collection<PSObject>();
            try
            {
                results = pipeline.Invoke();
            }
            catch (RuntimeException e)
            {
                log.Log(String.Join("\r\n", results.Select(x => x.ToString())) + "\r\n" + e.Message.ToString(), true);
                return;
            }

            log.Log(String.Join("\r\n", results.Select(x => x.ToString())), pipeline.Error.Count > 0);
        }
예제 #24
0
        public static IEnumerable<string> FindMatches2(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            var truncatedCommand = TruncatedCommand2(command, out lastToken);

            var teCmd = new Command("TabExpansion");
            teCmd.Parameters.Add("line", command);
            teCmd.Parameters.Add("lastWord", lastToken);
            var teResult = session.ExecuteCommand(teCmd, false, true).Cast<string>();

            var result = new List<string>();
            WrapResults(truncatedCommand, teResult, result, aceResponse);

            var splitPathResult =
                (session.ExecuteScriptPart(string.Format("Split-Path \"{0}*\" -IsAbsolute", lastToken), false, true)
                    .FirstOrDefault());
            var isAbsolute = splitPathResult != null && (bool) splitPathResult;

            if (isAbsolute)
            {
                var commandLine = string.Format("Resolve-Path \"{0}*\"", lastToken);
                var psResults = session.ExecuteScriptPart(commandLine, false, true);
                var rpResult = psResults.Cast<PathInfo>().Select(p => p.Path);
                WrapResults(truncatedCommand, rpResult, result, aceResponse);
            }
            else
            {
                var commandLine = string.Format("Resolve-Path \"{0}*\" -Relative", lastToken);
                var rpResult = session.ExecuteScriptPart(commandLine, false, true).Cast<string>();
                WrapResults(truncatedCommand, rpResult, result, aceResponse);
            }

            return result;
        }
예제 #25
0
        //public static VirtualHardDiskInfo GetByPath(PowerShellManager powerShell, string vhdPath)
        //{
        //    VirtualHardDiskInfo info = null;
        //    var vmNames = new List<string>();

        //    Command cmd = new Command("Get-VM");

        //    Collection<PSObject> result = powerShell.Execute(cmd, true);

        //    if (result == null || result.Count == 0)
        //        return null;

        //    vmNames = result.Select(r => r.GetString("Name")).ToList();
        //    var drives = vmNames.SelectMany(n => Get(powerShell, n));

        //    return drives.FirstOrDefault(d=>d.Path == vhdPath);
        //}

        public static Collection<PSObject> GetPS(PowerShellManager powerShell, string vmname)
        {
            Command cmd = new Command("Get-VMHardDiskDrive");
            cmd.Parameters.Add("VMName", vmname);

            return powerShell.Execute(cmd, true);
        }
        private static List<RdsCollectionSetting> GetCollectionSettings(this Runspace runspace, string collectionName, string connectionBroker, string primaryDomainController, string param, out object[] errors)
        {
            Command cmd = new Command("Get-RDSessionCollectionConfiguration");
            cmd.Parameters.Add("CollectionName", collectionName);
            cmd.Parameters.Add("ConnectionBroker", connectionBroker);

            if (!string.IsNullOrEmpty(param))
            {
                cmd.Parameters.Add(param, true);
            }

            var psObject = ExecuteShellCommand(runspace, cmd, false, primaryDomainController, out errors).FirstOrDefault();

            var properties = typeof(RdsCollectionSettings).GetProperties().Select(p => p.Name.ToLower());
            var collectionSettings = new RdsCollectionSettings();
            var result = new List<RdsCollectionSetting>();

            if (psObject != null)
            {
                foreach (var prop in psObject.Properties)
                {                    
                    if (prop.Name.ToLower() != "id" && prop.Name.ToLower() != "rdscollectionid")
                    {
                        result.Add(new RdsCollectionSetting
                        {
                            PropertyName = prop.Name,
                            PropertyValue = prop.Value
                        });
                    }
                }
            }

            return result;
        }
예제 #27
0
        private Hashtable GetConfigRaw(string env, string scriptFilePath, string xmlDefn = null)
        {
            using (var runspace = RunspaceFactory.CreateRunspace())
            {
                using (var pipeline = runspace.CreatePipeline())
                {
                    var getConfigCmd = new Command(scriptFilePath);
                    var envParam = new CommandParameter("Env", env);
                    getConfigCmd.Parameters.Add(envParam);

                    if (xmlDefn != null)
                    {
                        var envFileContentParam = new CommandParameter("EnvFileContent", xmlDefn);
                        getConfigCmd.Parameters.Add(envFileContentParam);
                    }

                    pipeline.Commands.Add(getConfigCmd);
                    runspace.Open();

                    Collection<PSObject> results = pipeline.Invoke();
                    var res = results[0].BaseObject as Hashtable;
                    if (res == null)
                    {
                        throw new Exception("Missing Config");
                    }

                    return res;
                }
            }
        }
예제 #28
0
        public override bool Run()
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();

                var pipeline = runspace.CreatePipeline();
                var powershellCommand = new Command(new FileInfo(parameters.ScriptName).FullName);
                foreach (var parameter in ((IDictionary<string, object>)parameters))
                {
                    powershellCommand.Parameters.Add(new CommandParameter(parameter.Key, parameter.Value.ToString()));
                }
                pipeline.Commands.Add(powershellCommand);
                try
                {
                    var psObjects = pipeline.Invoke();
                    foreach (var obj in psObjects)
                    {
                        notificationService.Notify(parameters.ScriptName, obj == null ? String.Empty : obj.ToString(), NotificationType.Information);
                    }
                }
                catch (Exception ex)
                {
                    notificationService.Notify(parameters.ScriptName, ex.Message, NotificationType.Error);
                }
                runspace.Close();
            }
            return true;
        }
예제 #29
0
    //function to run Powershell commands
    public static void RunPowerShell(string psScript, string psParameters)
    {

      try
      {
        var runspaceConfiguration = RunspaceConfiguration.Create();
        var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();
        var pipeline = runspace.CreatePipeline();
        var myCommand = new Command(psScript);
        pipeline.Commands.Add(myCommand);
        if (!string.IsNullOrEmpty(psParameters))
        {
          var aryParameters = psParameters.Split(' ');
          for (var i = 0; i < aryParameters.Count(); i++)
          {
            myCommand.Parameters.Add(aryParameters[i].ToString(CultureInfo.InvariantCulture), aryParameters[i + 1].ToString(CultureInfo.InvariantCulture));
            i++;
          }
        }

        var scriptInvoker = new RunspaceInvoke(runspace);

        // Execute PowerShell script
        Collection<PSObject> results = pipeline.Invoke();
        runspace.Close();
        return;

      }
      catch (Exception e)
      {
        Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught running powershell:" + e);
      }
    }
 public static void Delete(PowerShellManager powerShell, string vmName, string server)
 {
     Command cmd = new Command("Remove-VM");
     cmd.Parameters.Add("Name", vmName);
     if (!string.IsNullOrEmpty(server)) cmd.Parameters.Add("ComputerName", server);
     cmd.Parameters.Add("Force");
     powerShell.Execute(cmd, false, true);
 }
예제 #31
0
        public static void Add(PowerShellManager powerShell, string vmName)
        {
            Command cmd = new Command("Add-VMDvdDrive");

            cmd.Parameters.Add("VMName", vmName);

            powerShell.Execute(cmd, true);
        }
예제 #32
0
        public static void RemoveVmReplication(PowerShellManager powerShell, string vmName, string server)
        {
            Command cmd = new Command("Remove-VMReplication");
            cmd.Parameters.Add("VmName", vmName);
            if (!string.IsNullOrEmpty(server)) cmd.Parameters.Add("ComputerName", server);

            powerShell.Execute(cmd, false);
        }
예제 #33
0
            public int Execute()
            {
                int error = 0;

                Runspace runspace = null;

                runspace = RunspaceFactory.CreateRunspace();
                runspace.Open();

                Pipeline pipeline = runspace.CreatePipeline();

                //Construct the powershell command and add it to the pipeline.
                String        parameter1    = "From the hosting application";
                StringBuilder commandString = new StringBuilder();

                commandString.Append(_scriptName);
                Command command = new System.Management.Automation.Runspaces.Command(commandString.ToString());

                Console.WriteLine("Command is \"{0}\"", commandString);

                // CommandParameter commandParameter = new CommandParameter("$FromHostApp",parameter1);
                CommandParameter commandParameter = new CommandParameter(null, parameter1);

                command.Parameters.Add(commandParameter);

                pipeline.Commands.Add(command);

                // Execute PowerShell script
                Console.WriteLine("Running script");
                Collection <PSObject> results = null;

                try
                {
                    results = pipeline.Invoke();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception from Invoke = {0}", ex.ToString());
                }

                if (results != null)
                {
                    StringBuilder resultsMessage = new StringBuilder();
                    foreach (PSObject result in results)
                    {
                        resultsMessage.Append(result.ToString());
                    }

                    Console.WriteLine("Results are:");
                    Console.WriteLine(resultsMessage);
                }

                //Close the runspace.
                runspace.Close();

                return(error);
            }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            try
            {
                var userPrincipalName = string.Format("{0}|{1}", ClaimIdentifier, this.UserName);


                LogVerbose("Querying UserProfile service");
                GetUserProfileInformation(userPrincipalName);



                LogVerbose("Querying UserProfiles.PeopleManager");
                GetUserInformation(userPrincipalName);


                using (var runspace = new SPIaCRunspaceWithDelegate(SPIaCConnection.CurrentConnection))
                {
                    LogVerbose("Executing runspace to query Get-MSOLUser(-UserPrincipalName {0})", this.UserName);

                    var getUserCommand = new PCommand.Command("Get-MsolUser");
                    getUserCommand.Parameters.Add((new PCommand.CommandParameter("UserPrincipalName", this.UserName)));

                    var results = runspace.ExecuteRunspace(getUserCommand, string.Format("Unable to get user with UserPrincipalName : " + userPrincipalName));
                    if (results.Count() > 0)
                    {
                        foreach (PSObject itemUser in results)
                        {
                            var userProperties = itemUser.Properties;

                            GetPSObjectValue(userProperties, "DisplayName");
                            GetPSObjectValue(userProperties, "FirstName");
                            GetPSObjectValue(userProperties, "LastName");
                            GetPSObjectValue(userProperties, "UserPrincipalName");
                            GetPSObjectValue(userProperties, "Department");
                            GetPSObjectValue(userProperties, "Country");
                            GetPSObjectValue(userProperties, "UsageLocation");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed to execute QueryUserProfile in tenant {0}", this.ClientContext.Url);
            }
        }
예제 #35
0
        public SPIaCRunspaceWithDelegate(SPIaCConnection connection)
        {
            // Create Initial Session State for runspace.
            InitialSessionState initialSession = InitialSessionState.CreateDefault();

            initialSession.ImportPSModule(new[] { "MSOnline" });

            // Create credential object.
            var credential = connection.GetActiveCredentials();

            // Create command to connect office 365.
            connectCommand = new PCommand.Command("Connect-MsolService");
            connectCommand.Parameters.Add((new CommandParameter("Credential", credential)));

            psRunSpace = RunspaceFactory.CreateRunspace(initialSession);
            // Open runspace.
            psRunSpace.Open();
        }
예제 #36
0
        /// <summary>
        /// Initializes the run space for the <paramref name="moduleName"/>
        ///     This module connection property must require Credentials
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="moduleName"></param>
        /// <param name="connectionCommand"></param>
        public void Initialize(SPIaCConnection connection, string moduleName, string connectionCommand)
        {
            // Create Initial Session State for runspace.
            InitialSessionState initialSession = InitialSessionState.CreateDefault();

            initialSession.ImportPSModule(new[] { moduleName });

            // Create credential object.
            var credential = connection.GetActiveCredentials();

            // Create command to connect office 365.
            connectCommand = new PCommand.Command(connectionCommand);
            connectCommand.Parameters.Add((new CommandParameter("Credential", credential)));

            psRunSpace = RunspaceFactory.CreateRunspace(initialSession);
            // Open runspace.
            psRunSpace.Open();
        }
예제 #37
0
        public void BeforeEachTest()
        {
            var sessionState = InitialSessionState.CreateDefault();

            sessionState.Commands.Add(new SessionStateCmdletEntry("Test-SqlDatabase", typeof(SomeSqlDatabaseCmdLet), null));

            _runSpace = RunspaceFactory.CreateRunspace(sessionState);
            _runSpace.Open();

            _powerShell          = System.Management.Automation.PowerShell.Create();
            _powerShell.Runspace = _runSpace;

            _invokeSqlDatabase = new Command("Test-SqlDatabase");
            _powerShell.Commands.AddCommand(_invokeSqlDatabase);

            var program = new Mock <ISqlDatabaseProgram>(MockBehavior.Strict);

            program
            .Setup(p => p.ExecuteCommand(It.IsNotNull <CommandLine>()))
            .Callback <CommandLine>(cmd => _commandLines.Add(cmd));

            _commandLines.Clear();
            SqlDatabaseCmdLet.Program = program.Object;
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            var models = new List <SPGroupDefinitionModel>();

            try
            {
                using (var runspace = new SPIaCRunspaceWithDelegate())
                {
                    runspace.Initialize(SPIaCConnection.CurrentConnection, "MSOnline", "Connect-MsolService");

                    var getGroupCommand = new PCommand.Command("Get-MSOLGroup");

                    if (string.IsNullOrEmpty(this.GroupId))
                    {
                        getGroupCommand.Parameters.Add((new PCommand.CommandParameter("All")));
                    }
                    else
                    {
                        getGroupCommand.Parameters.Add((new PCommand.CommandParameter("ObjectId", this.GroupId)));
                        getGroupCommand.Parameters.Add((new PCommand.CommandParameter("Verbose")));
                    }


                    LogVerbose("BEGIN ---------------");
                    LogVerbose("Executing runspace to query Get-MSOLGroup(-All) which will take a minute or two.");
                    var collectionOfGroups = runspace.ExecuteRunspace(getGroupCommand, string.Format("Unable to retrieve {0} groups", "All"));
                    LogVerbose("END ---------------");

                    if (collectionOfGroups.Count() > 0)
                    {
                        LogVerbose("MSOL Groups found {0}", collectionOfGroups.Count());

                        foreach (var itemGroup in collectionOfGroups)
                        {
                            var groupProperties = itemGroup.Properties;
                            var groupObjectId   = groupProperties.GetPSObjectValue("ObjectId");

                            var model = new SPGroupMSOnlineDefinition()
                            {
                                ObjectId         = groupObjectId,
                                Title            = groupProperties.GetPSObjectValue("CommonName"),
                                Description      = groupProperties.GetPSObjectValue("DisplayName"),
                                EmailAddress     = groupProperties.GetPSObjectValue("EmailAddress"),
                                GroupType        = groupProperties.GetPSObjectValue("GroupType"),
                                LastDirSyncTime  = groupProperties.GetPSObjectValue("LastDirSyncTime"),
                                ManagedBy        = groupProperties.GetPSObjectValue("ManagedBy"),
                                ValidationStatus = groupProperties.GetPSObjectValue("ValidationStatus"),
                                IsSystem         = groupProperties.GetPSObjectValue("IsSystem")
                            };


                            if (GroupMembership)
                            {
                                var getGroupMembershipCommand = new PCommand.Command("Get-MsolGroupMember");
                                getGroupMembershipCommand.Parameters.Add((new PCommand.CommandParameter("GroupObjectId", groupObjectId)));
                                getGroupMembershipCommand.Parameters.Add((new PCommand.CommandParameter("Verbose")));

                                LogVerbose("BEGIN ---------------");
                                LogVerbose("Executing runspace to query Get-MsolGroupMember(-GroupObjectId {0}).", groupObjectId);
                                var groupMembershipResults = runspace.ExecuteRunspace(getGroupMembershipCommand, string.Format("Unable to retrieve {0} group membership", this.GroupId));
                                if (groupMembershipResults.Count() > 0)
                                {
                                    foreach (var itemMember in groupMembershipResults)
                                    {
                                        var memberProperties = itemMember.Properties;
                                        var userModel        = new SPUserDefinitionModel()
                                        {
                                            UserName         = memberProperties.GetPSObjectValue("CommonName"),
                                            UserDisplay      = memberProperties.GetPSObjectValue("DisplayName"),
                                            UserEmail        = memberProperties.GetPSObjectValue("EmailAddress"),
                                            Organization     = memberProperties.GetPSObjectValue("GroupMemberType"),
                                            MSOnlineObjectId = memberProperties.GetPSObjectValue("ObjectId")
                                        };
                                        model.Users.Add(userModel);
                                    }
                                }
                            }

                            models.Add(model);
                        }
                    }
                }

                models.ForEach(groups => WriteObject(groups));
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed to execute QueryUserProfile in tenant {0}", this.ClientContext.Url);
            }
        }
예제 #39
0
        private void tsbRun_Click(object sender, EventArgs e)
        {
            String mPsScript;
            int    mWidth = 150;

            if (this.txtPSScript.SelectedText.Length > 0)
            {
                mPsScript = this.txtPSScript.SelectedText;
            }
            else
            {
                mPsScript = this.txtPSScript.Text;
            }

            // maintain a single runspace for the life of the window
            if (myRunspace == null)
            {
                myRunspace = RunspaceFactory.CreateRunspace();
                myRunspace.ApartmentState = System.Threading.ApartmentState.STA;
                myRunspace.ThreadOptions  = PSThreadOptions.ReuseThread;
                myRunspace.Open();
                // Add variables into the current Powershell session
                myRunspace.SessionStateProxy.SetVariable("CurrentDB", this.CurrentDB);
            }
            Pipeline psPipeline = null;

            try
            {
                psPipeline = myRunspace.CreatePipeline();

                psPipeline.Commands.AddScript(mPsScript);
                System.Management.Automation.Runspaces.Command outString = new System.Management.Automation.Runspaces.Command("out-string");
                outString.Parameters.Add("width", mWidth);
                psPipeline.Commands.Add(outString);
            }
            catch (Exception ex)
            {
                rtbOutput.AppendText("\nERROR: " + ex.Message + "\n");
            }

            try
            {
                System.Collections.ObjectModel.Collection <PSObject> output = RunPowerShell(psPipeline);
                //System.Collections.ObjectModel.Collection<PSObject> output = psPipeline.Invoke();


                foreach (PSObject pso in output)
                {
                    if (isCancelled)
                    {
                        break;
                    }
                    rtbOutput.AppendText(pso.ToString());
                }
            }
            catch (Exception ex)
            {
                rtbOutput.AppendText("\nERROR: " + ex.Message);
            }
            finally
            {
                //myRunspace.Close();
                ScrollToBottom();
            }
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            try
            {
                using (var runspace = new SPIaCRunspaceWithDelegate(SPIaCConnection.CurrentConnection))
                {
                    if (string.IsNullOrEmpty(this.GroupId))
                    {
                        var getGroupAllCommand = new PCommand.Command("Get-MSOLGroup");
                        getGroupAllCommand.Parameters.Add((new PCommand.CommandParameter("All")));

                        LogVerbose("BEGIN ---------------");
                        LogVerbose("Executing runspace to query Get-MSOLGroup(-All) which will take a minute or two.");
                        var groupAllResults = runspace.ExecuteRunspace(getGroupAllCommand, string.Format("Unable to retrieve {0} groups", "All"));
                        if (groupAllResults.Count() > 0)
                        {
                            LogVerbose("MSOL Groups found {0}", groupAllResults.Count());
                        }
                        LogVerbose("END ---------------");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(this.SiteUrl))
                        {
                            using (var thisContext = this.ClientContext.Clone(this.SiteUrl))
                            {
                                thisContext.Credentials = this.ClientContext.Credentials;

                                var qroups = thisContext.Web.SiteGroups;
                                thisContext.Load(qroups);

                                var groupName = qroups.GetByName(this.GroupName);
                                thisContext.Load(groupName, gg => gg.LoginName, gg => gg.Title, gg => gg.Users);
                                thisContext.ExecuteQuery();
                                LogVerbose("Group {0} found in Site {1}", groupName.Title, this.SiteUrl);
                                foreach (var user in groupName.Users)
                                {
                                    LogVerbose("LoginName {0}", user.LoginName);
                                    LogVerbose("Email {0}", user.Email);
                                    LogVerbose("Id {0}", user.Id);
                                    LogVerbose("PrincipalType {0}", user.PrincipalType);
                                    LogVerbose("Title {0}", user.Title);
                                    LogVerbose("UserId {0}", user.UserId);
                                }
                            }
                        }

                        var getGroupCommand = new PCommand.Command("Get-MSOLGroup");
                        getGroupCommand.Parameters.Add((new PCommand.CommandParameter("ObjectId", this.GroupId)));
                        getGroupCommand.Parameters.Add((new PCommand.CommandParameter("Verbose")));

                        LogVerbose("BEGIN ---------------");
                        LogVerbose("Executing runspace to query Get-MSOLGroup(-SearchString {0}).", this.GroupId);
                        var groupresults = runspace.ExecuteRunspace(getGroupCommand, string.Format("Unable to retrieve {0} groups", this.GroupId));
                        if (groupresults.Count() > 0)
                        {
                            foreach (var itemGroup in groupresults)
                            {
                                var groupProperties = itemGroup.Properties;
                                var groupObjectId   = GetPSObjectValue(groupProperties, "ObjectId");

                                GetPSObjectValue(groupProperties, "CommonName");
                                GetPSObjectValue(groupProperties, "DisplayName");
                                GetPSObjectValue(groupProperties, "EmailAddress");
                                GetPSObjectValue(groupProperties, "GroupType");
                                GetPSObjectValue(groupProperties, "LastDirSyncTime");
                                GetPSObjectValue(groupProperties, "ManagedBy");
                                GetPSObjectValue(groupProperties, "ValidationStatus");
                                GetPSObjectValue(groupProperties, "IsSystem");

                                if (GroupMembership)
                                {
                                    var getGroupMembershipCommand = new PCommand.Command("Get-MsolGroupMember");
                                    getGroupMembershipCommand.Parameters.Add((new PCommand.CommandParameter("GroupObjectId", groupObjectId)));
                                    getGroupMembershipCommand.Parameters.Add((new PCommand.CommandParameter("Verbose")));

                                    LogVerbose("BEGIN ---------------");
                                    LogVerbose("Executing runspace to query Get-MsolGroupMember(-GroupObjectId {0}).", groupObjectId);
                                    var groupMembershipResults = runspace.ExecuteRunspace(getGroupMembershipCommand, string.Format("Unable to retrieve {0} group membership", this.GroupId));
                                    if (groupMembershipResults.Count() > 0)
                                    {
                                        foreach (var itemMember in groupMembershipResults)
                                        {
                                            var memberProperties = itemMember.Properties;

                                            GetPSObjectValue(memberProperties, "CommonName");
                                            GetPSObjectValue(memberProperties, "DisplayName");
                                            GetPSObjectValue(memberProperties, "EmailAddress");
                                            GetPSObjectValue(memberProperties, "GroupMemberType");
                                            GetPSObjectValue(memberProperties, "ObjectId");
                                        }
                                    }
                                    LogVerbose("END ---------------");
                                }
                            }
                        }
                        LogVerbose("END ---------------");
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed to execute QueryUserProfile in tenant {0}", this.ClientContext.Url);
            }
        }