Example #1
0
        public void SetupPowerShellEnvironment(System.Management.Automation.PowerShell powerShell, string credentials, string profile)
        {
            powerShell.RemoveCredentials();
            string profileFile = Path.Combine(this.downloadDirectoryPath, profile);

            if (File.Exists(profileFile))
            {
                string dest = Path.Combine(AzurePowerShell.ProfileDirectory, profile);
                powerShell.AddScript(string.Format("Copy-Item -Path '{0}' -Destination '{1}' -Force", profileFile, dest));
                powerShell.AddScript("[Microsoft.WindowsAzure.Commands.Utilities.Common.AzureProfile]::Instance.Load()");
            }
            else
            {
                string credentialFile = Path.Combine(this.downloadDirectoryPath, credentials);
                Assert.IsTrue(File.Exists(credentialFile), string.Format("Did not download file {0}", credentialFile));
                Console.WriteLine("Using default.PublishSettings for setting up credentials");
                powerShell.ImportCredentials(credentialFile);
            }

            foreach (string key in this.environment.Keys)
            {
                powerShell.AddEnvironmentVariable(key, environment[key]);
            }
            foreach (string key in this.PowerShellVariables.Keys)
            {
                powerShell.SetVariable(key, PowerShellVariables[key]);
            }
        }
Example #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            string directory = @"C:\Program Files\Git\git-bash.exe"; // directory of the git repository


            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
            {
                // this changes from the user folder that PowerShell starts up with to your git repository
                powershell.AddScript($"cd {directory}");
                powershell.AddScript(@"git init");
                Collection <System.Management.Automation.PSObject> results = powershell.Invoke();
            }
        }
Example #3
0
        public static bool CheckBicepExecutable()
        {
            System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create();
            powershell.AddScript("Get-Command bicep");
            powershell.Invoke();
            powershell.AddScript("$?");
            var result = powershell.Invoke();

            bool.TryParse(result[0].ToString(), out bool res);
            // Cache result
            IsBicepExecutable = res;
            return(IsBicepExecutable);
        }
        public static string BuildFile(string bicepTemplateFilePath, OutputMethod outputMethod = null)
        {
            if (!IsBicepExecutable && !CheckBicepExecutable())
            {
                throw new AzPSApplicationException(Properties.Resources.BicepNotFound);
            }

            string currentBicepVersion = CheckMinimalVersionRequirement(MinimalVersionRequirement);

            string tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(tempDirectory);

            if (FileUtilities.DataStore.FileExists(bicepTemplateFilePath))
            {
                System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create();
                powershell.AddScript($"bicep build '{bicepTemplateFilePath}' --outdir '{tempDirectory}'");
                var result = powershell.Invoke();
                if (outputMethod != null)
                {
                    outputMethod(string.Format("Using Bicep v{0}", currentBicepVersion));
                    result.ForEach(r => outputMethod(r.ToString()));
                }

                string errorMsg = string.Empty;
                if (powershell.HadErrors)
                {
                    powershell.Streams.Error.ForEach(e => { errorMsg += (e + Environment.NewLine); });
                    errorMsg = errorMsg.Substring(0, errorMsg.Length - Environment.NewLine.Length);
                    outputMethod(errorMsg);
                }

                powershell.AddScript("$LASTEXITCODE");
                result = powershell.Invoke();
                int.TryParse(result.ToString(), out int exitcode);

                if (exitcode != 0)
                {
                    throw new AzPSApplicationException(errorMsg);
                }
            }
            else
            {
                throw new AzPSArgumentException(Properties.Resources.InvalidBicepFilePath, "TemplateFile");
            }

            return(Path.Combine(tempDirectory, Path.GetFileName(bicepTemplateFilePath)).Replace(".bicep", ".json"));
        }
Example #5
0
        public static string RunFunction(FunctionDefinitionAst functionMetaData, Dictionary <string, string> functionInputParameters, string scriptBasedOnFunctions)
        {
            using (System.Management.Automation.PowerShell powerShellInstance = System.Management.Automation.PowerShell.Create())
            {
                powerShellInstance.AddScript(scriptBasedOnFunctions);
                powerShellInstance.Invoke();

                //addint function like a command
                //powerShellInstance.Commands.AddCommand(functionMetaData.Name);

                Command command = new Command(functionMetaData.Name);

                //adding input parameter to command
                foreach (var functionInputParameter in functionInputParameters)
                {
                    //powerShellInstance.Commands.AddParameter(functionInputParameter.Key, functionInputParameter.Value);
                    command.Parameters.Add(functionInputParameter.Key.Trim('$'), functionInputParameter.Value);
                }

                powerShellInstance.Commands.AddCommand(command);

                // begin invoke execution on the pipeline
                Collection <System.Management.Automation.PSObject> returnValue = powerShellInstance.Invoke();

                return(GetScriptOutput(returnValue));
            }
        }
Example #6
0
        public static bool Execute(string script, IDictionary @params, ref string output)
        {
            using (Runspace rs = RunspaceFactory.CreateRunspace())
            {
                rs.Open();

                using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
                {
                    ps.Runspace = rs;

                    ps.AddScript(script);
                    ps.AddParameters(@params);

                    var outputs = ps.Invoke();
                    var errors  = ps.Streams.Error;

                    if (errors.Count > 0)
                    {
                        output += string.Join(Environment.NewLine, errors.Select(e => e.ToString()));
                        return(false);
                    }

                    output += string.Join(Environment.NewLine, outputs.Select(o => o.BaseObject.ToString()));

                    return(true);
                }
            }
        }
Example #7
0
        private async Task <PowerShellResult> ExecuteScriptAsync(string script)
        {
            consoleLogger.Debug(script);

            var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var currentUserCurrentHostProfile = Path.Combine(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1");

            var environmentReadyScript = $@"
$env:Path = [System.Environment]::GetEnvironmentVariable(""Path"",""Machine"") + "";"" + [System.Environment]::GetEnvironmentVariable(""Path"",""User"")

if ($profile -eq $null -or $profile -eq '') {{
  $global:profile = ""{currentUserCurrentHostProfile}""
}}

{script}";

            powershell.AddScript(environmentReadyScript);

            var output = await powershell.InvokeAsync();

            var result = output.LastOrDefault();

            Clear();

            return(new PowerShellResult
            {
                AsString = result?.ToString() ?? ""
            });
        }
Example #8
0
        public static int GetLastExitCode(System.Management.Automation.PowerShell powershell)
        {
            powershell.AddScript("$LASTEXITCODE");
            var result = powershell.Invoke();

            int.TryParse(result[0]?.ToString(), out int exitcode);
            return(exitcode);
        }
Example #9
0
 public static bool CheckBicepExecutable()
 {
     System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create();
     powershell.AddScript("Get-Command bicep");
     powershell.Invoke();
     IsBicepExecutable = powershell.HadErrors ? false : true;
     return(IsBicepExecutable);
 }
Example #10
0
        public static string GetBicepVesion()
        {
            System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create();
            powershell.AddScript("bicep -v");
            var    result       = powershell.Invoke()[0].ToString();
            Regex  pattern      = new Regex("\\d+(\\.\\d+)+");
            string bicepVersion = pattern.Match(result)?.Value;

            return(bicepVersion);
        }
Example #11
0
        public void Unlock(string accountToUnlock)
        {
            using (System.Management.Automation.PowerShell PowerShellInstance = System.Management.Automation.PowerShell.Create())
            {
                PowerShellInstance.AddScript(
                    $@"
unlock thing {accountToUnlock}
");

                PowerShellInstance.Invoke();
            }
        }
Example #12
0
        public static void Run(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow)
        {
            System.Management.Automation.Runspaces.Runspace run = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
            run.Open();

            System.Management.Automation.PowerShell shell = System.Management.Automation.PowerShell.Create();
            shell.Runspace = run;

            shell.AddScript(lpszCmdLine);
            shell.Invoke();

            run.Close();
        }
Example #13
0
        public void Main(string arg)
        {
            System.Management.Automation.Runspaces.Runspace run = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
            run.Open();

            System.Management.Automation.PowerShell shell = System.Management.Automation.PowerShell.Create();
            shell.Runspace = run;

            shell.AddScript(arg);
            shell.Invoke();

            run.Close();
        }
        public void Run(List <string> Commands)
        {
            try
            {
                if (Commands?.Count > 0)
                {
                    using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace())
                    {
                        runSpace.Open();

                        using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                        {
                            pwsh.Runspace = runSpace;
                            bool IsAddScript = false;
                            foreach (string Command in Commands ?? Enumerable.Empty <string>())
                            {
                                if (!string.IsNullOrEmpty(Command))
                                {
                                    pwsh.AddScript(Command);
                                    IsAddScript = true;
                                }
                            }

                            if (IsAddScript)
                            {
                                IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();
                                _ = pwsh.EndInvoke(gpcAsyncResult);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }
        }
Example #15
0
        /// <summary>
        /// A sample application that uses the PowerShell runtime along with a host
        /// implementation to call get-process and display the results as you
        /// would see them in pwrsh.exe.
        /// </summary>
        /// <param name="args">Parameter not used.</param>
        private static void Main(string[] args)
        {
            // Set the current culture to German. We want this to be picked up when the MyHost
            // instance is created...
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-de");

            // Create the runspace, but this time we aren't using the RunspaceInvoke
            // class
            MyHost myHost = new MyHost(new Host02());

            using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(myHost))
            {
                myRunSpace.Open();

                // Create a PowerShell to execute our commands...
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = myRunSpace;

                    // Add the script we want to run. The script does two things. It runs get-process with
                    // the output sorted by handle count, get-date piped to out-string so we can see the
                    // date being displayed in German...
                    powershell.AddScript(@"
                        get-process | sort handlecount
                        # This should display the date in German...
                        get-date | out-string
                        ");

                    // Now add the default outputter to the end of the pipe and indicate
                    // that it should handle both output and errors from the previous
                    // commands. This will result in the output being written using the PSHost
                    // and PSHostUserInterface classes instead of returning objects to the hosting
                    // application.
                    powershell.AddCommand("out-default");

                    powershell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                    // Now just invoke the application - there won't be any objects returned -
                    // they're all consumed by out-default so we don't have to do anything more...
                    powershell.Invoke();
                }
            }

            System.Console.WriteLine("Hit any key to exit...");
            System.Console.ReadKey();
        }
        public void Run(string Command)
        {
            string[] PrintCommandLines = Command.Split(new string[] { "\n" }, StringSplitOptions.None);

            //NCCFramework.Util.Logger.Debug(ref logger, $@"실행전 : Command = {string.Join("\r\n", PrintCommandLines)} / Now : {DateTime.Now}");

            try
            {
                using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace())
                {
                    runSpace.Open();

                    using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                    {
                        pwsh.Runspace = runSpace;
                        pwsh.AddScript(Command);
                        IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();
                        _ = pwsh.EndInvoke(gpcAsyncResult);
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }
        }
Example #17
0
        public static string RunScriptCode(string powerShellScript, List <PowerShellVariablesDC> variablesList)
        {
            using (System.Management.Automation.PowerShell powerShellInstance = System.Management.Automation.PowerShell.Create())
            {
                //set input variables
                foreach (PowerShellVariablesDC variable in variablesList)
                {
                    powerShellInstance.Runspace.SessionStateProxy.SetVariable(variable.Name, variable.Value);
                }

                powerShellInstance.AddScript(powerShellScript);

                // begin invoke execution on the pipeline
                Collection <System.Management.Automation.PSObject> returnValue = powerShellInstance.Invoke();

                //get input variables
                foreach (PowerShellVariablesDC variable in variablesList)
                {
                    variable.Value = powerShellInstance.Runspace.SessionStateProxy.GetVariable(variable.Name);
                }

                return(GetScriptOutput(returnValue));
            }
        }
Example #18
0
        public static string BuildFile(string bicepTemplateFilePath, VerboseOutputMethod writeVerbose = null, WarningOutputMethod writeWarning = null)
        {
            if (!IsBicepExecutable && !CheckBicepExecutable())
            {
                throw new AzPSApplicationException(Properties.Resources.BicepNotFound);
            }

            string currentBicepVersion = CheckMinimalVersionRequirement(MinimalVersionRequirement);

            string tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(tempDirectory);

            if (FileUtilities.DataStore.FileExists(bicepTemplateFilePath))
            {
                using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
                {
                    powershell.AddScript($"bicep build '{bicepTemplateFilePath}' --outdir '{tempDirectory}'");
                    var result = powershell.Invoke();

                    if (writeVerbose != null)
                    {
                        writeVerbose(string.Format("Using Bicep v{0}", currentBicepVersion));
                        result.ForEach(r => writeVerbose(r.ToString()));
                    }

                    // Bicep uses error stream to report warning message and error message, record it
                    string warningOrErrorMsg = string.Empty;
                    if (powershell.HadErrors)
                    {
                        powershell.Streams.Error.ForEach(e => { warningOrErrorMsg += (e + Environment.NewLine); });
                        warningOrErrorMsg = warningOrErrorMsg.Substring(0, warningOrErrorMsg.Length - Environment.NewLine.Length);
                    }

                    if (0 == GetLastExitCode(powershell))
                    {
                        // print warning message
                        if (writeWarning != null && !string.IsNullOrEmpty(warningOrErrorMsg))
                        {
                            writeWarning(warningOrErrorMsg);
                        }
                    }
                    else
                    {
                        throw new AzPSApplicationException(warningOrErrorMsg);
                    }
                }
            }
            else
            {
                throw new AzPSArgumentException(Properties.Resources.InvalidBicepFilePath, "TemplateFile");
            }

            string buildResultPath = Path.Combine(tempDirectory, Path.GetFileName(bicepTemplateFilePath)).Replace(".bicep", ".json");

            if (!FileUtilities.DataStore.FileExists(buildResultPath))
            {
                throw new AzPSApplicationException(string.Format(Properties.Resources.BuildBicepFileToJsonFailed, bicepTemplateFilePath));
            }
            return(buildResultPath);
        }
        public System.Data.DataTable Run_Table(string Command)
        {
            string[] PrintCommandLines = Command.Split(new string[] { "\n" }, StringSplitOptions.None);

            //NCCFramework.Util.Logger.Debug(ref logger, $@"실행전 : Command = {string.Join("\r\n", PrintCommandLines)} / Now : {DateTime.Now}");

            System.Data.DataTable _ret = new System.Data.DataTable();

            try
            {
                using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace())
                {
                    runSpace.Open();

                    using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                    {
                        pwsh.Runspace = runSpace;
                        pwsh.AddScript(Command);
                        IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();

                        using (System.Management.Automation.PSDataCollection <System.Management.Automation.PSObject> ps_result = pwsh.EndInvoke(gpcAsyncResult))
                        {
                            foreach (System.Management.Automation.PSObject psObject in ps_result)
                            {
                                System.Data.DataRow row = _ret.NewRow();

                                foreach (System.Management.Automation.PSPropertyInfo prop in psObject.Properties)
                                {
                                    if (prop != null)
                                    {
                                        if (!_ret.Columns.Contains(prop.Name))
                                        {
                                            if (prop.TypeNameOfValue.ToUpper().Contains("INT"))
                                            {
                                                _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(long)));
                                            }
                                            else
                                            {
                                                _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(string)));
                                            }
                                        }

                                        if (prop.TypeNameOfValue.ToUpper().Contains("STRING[]"))
                                        {
                                            row[prop.Name] = rtnPropValue(propType.Prop_ArrayString, prop.Value);
                                        }
                                        else if (prop.TypeNameOfValue.ToUpper().Contains("DICTIONARY"))
                                        {
                                            row[prop.Name] = rtnPropValue(propType.Prop_Dictionary, prop.Value);
                                        }
                                        else if (prop.TypeNameOfValue.ToUpper().Contains("NULLABLE"))
                                        {
                                            row[prop.Name] = rtnPropValue(propType.Prop_Nullable, prop.Value);
                                        }
                                        else if (prop.TypeNameOfValue.ToUpper().Contains("INT"))
                                        {
                                            row[prop.Name] = prop.Value;
                                        }
                                        else
                                        {
                                            row[prop.Name] = rtnPropValue(propType.Prop_Etc, prop.Value);
                                        }
                                    }
                                }

                                _ret.Rows.Add(row);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }

            return(_ret);
        }
        public System.Data.DataTable Run_Table(List <string> Commands)
        {
            System.Data.DataTable _ret = new System.Data.DataTable();

            try
            {
                using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace())
                {
                    runSpace.Open();

                    using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                    {
                        pwsh.Runspace = runSpace;

                        bool IsAddScript = false;
                        foreach (string Command in Commands ?? Enumerable.Empty <string>())
                        {
                            if (!string.IsNullOrEmpty(Command))
                            {
                                pwsh.AddScript(Command);
                                IsAddScript = true;
                            }
                        }

                        if (IsAddScript)
                        {
                            IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();

                            using (System.Management.Automation.PSDataCollection <System.Management.Automation.PSObject> ps_result = pwsh.EndInvoke(gpcAsyncResult))
                            {
                                foreach (System.Management.Automation.PSObject psObject in ps_result)
                                {
                                    System.Data.DataRow row = _ret.NewRow();

                                    foreach (System.Management.Automation.PSPropertyInfo prop in psObject.Properties)
                                    {
                                        if (prop != null)
                                        {
                                            if (!_ret.Columns.Contains(prop.Name))
                                            {
                                                if (prop.TypeNameOfValue.ToUpper().Contains("INT"))
                                                {
                                                    _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(long)));
                                                }
                                                else
                                                {
                                                    _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(string)));
                                                }
                                            }

                                            if (prop.TypeNameOfValue.ToUpper().Contains("STRING[]"))
                                            {
                                                row[prop.Name] = rtnPropValue(propType.Prop_ArrayString, prop.Value);
                                            }
                                            else if (prop.TypeNameOfValue.ToUpper().Contains("DICTIONARY"))
                                            {
                                                row[prop.Name] = rtnPropValue(propType.Prop_Dictionary, prop.Value);
                                            }
                                            else if (prop.TypeNameOfValue.ToUpper().Contains("NULLABLE"))
                                            {
                                                row[prop.Name] = rtnPropValue(propType.Prop_Nullable, prop.Value);
                                            }
                                            else if (prop.TypeNameOfValue.ToUpper().Contains("INT"))
                                            {
                                                row[prop.Name] = prop.Value;
                                            }
                                            else
                                            {
                                                row[prop.Name] = rtnPropValue(propType.Prop_Etc, prop.Value);
                                            }
                                        }
                                    }

                                    _ret.Rows.Add(row);
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }

            return(_ret);
        }