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)); } }
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")); }
internal RemoteHelpInfo( ExecutionContext context, RemoteRunspace remoteRunspace, string remoteHelpTopic, string remoteHelpCategory, HelpCategory localHelpCategory) : base(localHelpCategory) { using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create()) { powerShell.AddCommand("Get-Help"); powerShell.AddParameter("Name", (object)remoteHelpTopic); if (!string.IsNullOrEmpty(remoteHelpCategory)) { powerShell.AddParameter("Category", (object)remoteHelpCategory); } powerShell.Runspace = (Runspace)remoteRunspace; Collection <PSObject> collection; using (new PowerShellStopper(context, powerShell)) { using (RemoteHelpInfo.tracer.TraceScope("Downloading remote help for {0}", (object)remoteHelpTopic)) collection = powerShell.Invoke(); } this.deserializedRemoteHelp = collection != null && collection.Count != 0 ? collection[0] : throw new HelpNotFoundException(remoteHelpTopic); this.deserializedRemoteHelp.TypeNames.Clear(); this.deserializedRemoteHelp.TypeNames.Add("MamlCommandHelpInfo"); this.deserializedRemoteHelp.TypeNames.Add("HelpInfo"); this.deserializedRemoteHelp.Methods.Remove("ToString"); } }
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); } } }
/// <summary> /// Construct a new AnalysisService. /// </summary> /// <param name="loggerFactory">Logger factory to create logger instances with.</param> /// <param name="languageServer">The LSP language server for notifications.</param> /// <param name="configurationService">The configuration service to query for configurations.</param> /// <param name="workspaceService">The workspace service for file handling within a workspace.</param> public AnalysisService( ILoggerFactory loggerFactory, ILanguageServer languageServer, ConfigurationService configurationService, WorkspaceService workspaceService) { _loggerFactory = loggerFactory; _logger = loggerFactory.CreateLogger <AnalysisService>(); _languageServer = languageServer; _configurationService = configurationService; _workplaceService = workspaceService; _analysisDelayMillis = 750; _mostRecentCorrectionsByFile = new ConcurrentDictionary <ScriptFile, CorrectionTableEntry>(); _analysisEngineLazy = new Lazy <PssaCmdletAnalysisEngine>(InstantiateAnalysisEngine); _pssaSettingsFilePath = null; _azureRmVersion = "6.13.1"; _azVersion = "4.6.1"; powerShell = System.Management.Automation.PowerShell.Create() .AddScript("Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process") .AddScript("Register-PSRepository -Name PSGallery -SourceLocation https://www.powershellgallery.com/api/v2/ -InstallationPolicy Trusted") .AddScript(@"Install-Module -Name Az.Tools.Migration -Repository PSGallery") .AddScript("$azSpec = Get-AzUpgradeCmdletSpec -ModuleName \"Az\" -ModuleVersion \"" + _azVersion + "\"") .AddScript("$azureRMSpec = Get-AzUpgradeCmdletSpec -ModuleName \"AzureRM\" -ModuleVersion \"" + _azureRmVersion + "\""); powerShell.Invoke(); }
public AbstractCmdletTest() { _pwrSh = System.Management.Automation.PowerShell.Create(); // Import Module _pwrSh.AddCommand("import-module"); _pwrSh.AddParameter("Name", "./Sentral.Api.PowerShell.dll"); _pwrSh.Invoke(); _pwrSh.Commands.Clear(); var settings = TestSettings.LoadSettings(); try { ConnectSentralApi.GetSentralAPIConnection(); } catch { var connection = new ConnectSentralApi() { BaseUrl = settings.BaseUrl, ApiKey = settings.ApiKey, TenantCode = settings.ApiTenant }; var enumerator = connection.Invoke().GetEnumerator(); while (enumerator.MoveNext()) { } } _isTestSite = settings.BaseUrl.Contains(".sentral.school/"); }
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); }
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); }
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); }
public void Unlock(string accountToUnlock) { using (System.Management.Automation.PowerShell PowerShellInstance = System.Management.Automation.PowerShell.Create()) { PowerShellInstance.AddScript( $@" unlock thing {accountToUnlock} "); PowerShellInstance.Invoke(); } }
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(); } }
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(); }
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(); }
protected Collection <T> RunScript <T>(string cmdletName, Dictionary <string, object> scriptParameters) { // specify the script code to run. _pwrSh.AddCommand(cmdletName); // specify the parameters to pass into the script. _pwrSh.AddParameters(scriptParameters); // execute the script and await the result. Collection <T> results = _pwrSh.Invoke <T>(); // Reset for next _pwrSh.Commands.Clear(); return(results); }
/// <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(); }
/// <summary> /// Takes script text as input and runs it /// </summary> /// <param name="scriptText"></param> private void RunScript(string scriptText) { using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create()) { powerShell.Commands.AddScript(scriptText); powerShell.AddParameter("serverName", ConfigurationManager.AppSettings["serverName"]); powerShell.AddParameter("batchName", ConfigurationManager.AppSettings["batchName"]); powerShell.AddParameter("batchParams", ConfigurationManager.AppSettings["batchParams"]); try { powerShell.Invoke(); } catch (Exception exp) { throw exp; } } }
/// <summary> /// Process markdown as path. /// </summary> /// <param name="parameter">Name of parameter to pass to `ConvertFrom-Markdown`.</param> /// <param name="input">Value of parameter.</param> private void ConvertFromMarkdown(string parameter, object input) { _powerShell.AddCommand("Microsoft.PowerShell.Utility\\ConvertFrom-Markdown").AddParameter(parameter, input); if (!UseBrowser) { _powerShell.AddParameter("AsVT100EncodedString"); } Collection <MarkdownInfo> output = _powerShell.Invoke <MarkdownInfo>(); if (_powerShell.HadErrors) { foreach (ErrorRecord errorRecord in _powerShell.Streams.Error) { WriteError(errorRecord); } } foreach (MarkdownInfo result in output) { ProcessMarkdownInfo(result); } }
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)); } }
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); }