protected override void ProcessRecord() { string fileValue = string.Empty; foreach (var obj in InputObject) { if (!Property.ContainsKey("file")) { continue; } if (Property["file"] is ScriptBlock) { using (PowerShell ps = PowerShell.Create(InitialSessionState.CreateDefault2())) { var result = ps.AddCommand("ForEach-Object").AddParameter("process", Property["file"]).Invoke(new[] { obj }); if (result.Count > 0) { fileValue = result[0].ToString(); } } } else { fileValue = Property["file"].ToString(); } _files.Add(fileValue); } }
/// <summary> /// Creates an instance of the AnalysisService class. /// </summary> /// <param name="consoleHost">An object that implements IConsoleHost in which to write errors/warnings /// from analyzer.</param> /// <param name="settingsPath">Path to a PSScriptAnalyzer settings file.</param> public AnalysisService(IConsoleHost consoleHost, string settingsPath = null) { try { // Attempt to create a ScriptAnalyzer instance first // just in case the assembly can't be found and we // can skip creating an extra runspace. this.scriptAnalyzer = new ScriptAnalyzer(); this.analysisRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); this.analysisRunspace.ApartmentState = ApartmentState.STA; this.analysisRunspace.ThreadOptions = PSThreadOptions.ReuseThread; this.analysisRunspace.Open(); this.scriptAnalyzer.Initialize( this.analysisRunspace, new AnalysisOutputWriter(consoleHost), includeRuleNames: settingsPath == null ? IncludedRules : null, includeDefaultRules: true, profile: settingsPath); } catch (FileNotFoundException) { Logger.Write( LogLevel.Warning, "Script Analyzer binaries not found, AnalysisService will be disabled."); } }
protected void LogEvent(EventTask task, EventId id, string context, string name, string version, string providerName, string source, string status, string destinationPath) { #if !UNIX var iis = InitialSessionState.CreateDefault2(); using (Runspace rs = RunspaceFactory.CreateRunspace(iis)) { using (PowerShell powershell = PowerShell.Create()) { try { rs.Open(); powershell.Runspace = rs; powershell.AddCommand(Constants.NewWinEvent); powershell.AddParameter("ProviderName", Constants.PowerShellProviderName); powershell.AddParameter("Id", id); powershell.AddParameter("Payload", new object[] { task.ToString(), string.Format(CultureInfo.InvariantCulture, "Package={0}, Version={1}, Provider={2}, Source={3}, Status={4}, DestinationPath={5}", name, version, providerName, source, status, destinationPath), context }); powershell.Invoke(); } catch (Exception ex) { Verbose(ex.Message); } } } #endif }
public static async Task <ConsoleOutput> ExecuteCommand(this Command command) { try { InitialSessionState iss = InitialSessionState.CreateDefault2(); using (Runspace rs = RunspaceFactory.CreateRunspace(iss)) { rs.Open(); using (PowerShell ps = PowerShell.Create()) { ps.Runspace = rs; ps.Commands.AddCommand(command); ps.Invoke(); var output = await ps.GetPowershellOutput(); return(output); } } } catch (Exception ex) { throw new Exception(ex.GetExceptionChain()); } }
/// <summary> /// Initializes a new instance of the PowerShellContext class and /// opens a runspace to be used for the session. /// </summary> /// <param name="hostDetails">Provides details about the host application.</param> public PowerShellContext(HostDetails hostDetails) { hostDetails = hostDetails ?? HostDetails.Default; this.psHost = new ConsoleServicePSHost(hostDetails); this.initialSessionState = InitialSessionState.CreateDefault2(); Runspace runspace = RunspaceFactory.CreateRunspace(psHost, this.initialSessionState); runspace.ApartmentState = ApartmentState.STA; runspace.ThreadOptions = PSThreadOptions.ReuseThread; runspace.Open(); this.ownsInitialRunspace = true; this.Initialize(hostDetails, runspace); // Use reflection to execute ConsoleVisibility.AlwaysCaptureApplicationIO = true; Type consoleVisibilityType = Type.GetType( "System.Management.Automation.ConsoleVisibility, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); if (consoleVisibilityType != null) { PropertyInfo propertyInfo = consoleVisibilityType.GetProperty( "AlwaysCaptureApplicationIO", BindingFlags.Static | BindingFlags.Public); if (propertyInfo != null) { propertyInfo.SetValue(null, true); } } }
/// <summary> /// Creates an instance of the AnalysisService class. /// </summary> /// <param name="settingsPath">Path to a PSScriptAnalyzer settings file.</param> /// <param name="logger">An ILogger implementation used for writing log messages.</param> public AnalysisService(string settingsPath, ILogger logger) { this.logger = logger; try { this.SettingsPath = settingsPath; scriptAnalyzerModuleInfo = FindPSScriptAnalyzerModule(logger); var sessionState = InitialSessionState.CreateDefault2(); sessionState.ImportPSModulesFromPath(scriptAnalyzerModuleInfo.ModuleBase); // runspacepool takes care of queuing commands for us so we do not // need to worry about executing concurrent commands this.analysisRunspacePool = RunspaceFactory.CreateRunspacePool(sessionState); // having more than one runspace doesn't block code formatting if one // runspace is occupied for diagnostics this.analysisRunspacePool.SetMaxRunspaces(NumRunspaces); this.analysisRunspacePool.ThreadOptions = PSThreadOptions.ReuseThread; this.analysisRunspacePool.Open(); ActiveRules = IncludedRules.ToArray(); EnumeratePSScriptAnalyzerCmdlets(); EnumeratePSScriptAnalyzerRules(); } catch (Exception e) { var sb = new StringBuilder(); sb.AppendLine("PSScriptAnalyzer cannot be imported, AnalysisService will be disabled."); sb.AppendLine(e.Message); this.logger.Write(LogLevel.Warning, sb.ToString()); } }
public static InitialSessionState GenerateInitialSessionState(System.Management.Automation.SessionState sessionState) { var initialSessionState = InitialSessionState.CreateDefault2(); var modulePaths = sessionState.InvokeCommand.InvokeScript("Get-Module").Select(m => m.BaseObject).Cast <PSModuleInfo>().Select(m => m.Path).ToArray(); initialSessionState.ImportPSModule(modulePaths); var commands = sessionState.InvokeCommand.InvokeScript("Get-ChildItem -Path Function:\\").Select(m => m.BaseObject).Cast <FunctionInfo>(); foreach (var command in commands) { initialSessionState.Commands.Add(new SessionStateFunctionEntry(command.Name, command.Definition)); } var variables = sessionState.InvokeCommand.InvokeScript("Get-Variable").Select(m => m.BaseObject).Cast <PSVariable>(); foreach (var variable in variables) { if (variable.Options.HasFlag(ScopedItemOptions.Constant) || variable.Options.HasFlag(ScopedItemOptions.ReadOnly)) { continue; } initialSessionState.Variables.Add(new SessionStateVariableEntry(variable.Name, variable.Value, variable.Description)); } return(initialSessionState); }
private void SetupRunspace() { // Unless you want to run commands from any built-in modules, using 'CreateDefault2' is enough. runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); runspace.Open(); Runspace.DefaultRunspace = runspace; }
public PowerShellKernel() { Name = DefaultKernelName; _cancellationSource = new CancellationTokenSource(); _lazyPwsh = new Lazy <PowerShell>(() => { //Sets the distribution channel to "PSES" so starts can be distinguished in PS7+ telemetry Environment.SetEnvironmentVariable("POWERSHELL_DISTRIBUTION_CHANNEL", "dotnet-interactive-powershell"); // Create PowerShell instance var iss = InitialSessionState.CreateDefault2(); if (Platform.IsWindows) { // This sets the execution policy on Windows to RemoteSigned. iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned; } var runspace = RunspaceFactory.CreateRunspace(iss); runspace.Open(); var pwsh = PowerShell.Create(runspace); // Add Modules directory that contains the helper modules string psModulePath = Environment.GetEnvironmentVariable("PSModulePath"); string psJupyterModulePath = Path.Join( Path.GetDirectoryName(typeof(PowerShellKernel).Assembly.Location), "Modules"); Environment.SetEnvironmentVariable("PSModulePath", $"{psJupyterModulePath}{Path.PathSeparator}{psModulePath}"); RegisterForDisposal(pwsh); return(pwsh); }); }
//Turn off hotspot 2.0 private void Hotspot2Clicked(object sender, RoutedEventArgs e) { using (var PowerShellInstance = PowerShell.Create(InitialSessionState.CreateDefault2())) { PowerShellInstance.AddScript( "Set-ItemProperty -Path HKLM:\\SOFTWARE\\Microsoft\\WlanSvc\\AnqpCache -Name OsuRegistrationStatus -Value 0" ); var result = PowerShellInstance.BeginInvoke(); while (result.IsCompleted == false) { Thread.Sleep(1000); } MessageBox.Show("Hotspot 2.0 Disabled", "Process Complete"); } /* * using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) * using (var key = hklm.OpenSubKey("SOFTWARE\\Microsoft\\WlanSvc\\AnqpCache", true)) * { * if (key != null) //must check for null key * { * key.SetValue("OsuRegistrationStatus", 0); * MessageBox.Show("Hotspot 2.0 Disabled", "Process Complete"); * } * } */ }
private PowerShell CreatePowerShell() { // Set the distribution channel so telemetry can be distinguished in PS7+ telemetry Environment.SetEnvironmentVariable(PSTelemetryEnvName, PSTelemetryChannel); // Create PowerShell instance var iss = InitialSessionState.CreateDefault2(); if (Platform.IsWindows) { // This sets the execution policy on Windows to RemoteSigned. iss.ExecutionPolicy = ExecutionPolicy.RemoteSigned; } // Set $PROFILE. var profileValue = DollarProfileHelper.GetProfileValue(); iss.Variables.Add(new SessionStateVariableEntry("PROFILE", profileValue, "The $PROFILE.")); var runspace = RunspaceFactory.CreateRunspace(_psHost, iss); runspace.Open(); var pwsh = PowerShell.Create(runspace); // Add Modules directory that contains the helper modules string psJupyterModulePath = Path.Join( Path.GetDirectoryName(typeof(PowerShellKernel).Assembly.Location), "Modules"); AddModulePath(psJupyterModulePath); RegisterForDisposal(pwsh); return(pwsh); }
public void TestRunspaceWithPowerShellAndInitialSessionState() { InitialSessionState iss = InitialSessionState.CreateDefault2(); // NOTE: instantiate custom host myHost for the next line to capture stdout and stderr output // in addition to just the PSObjects using (Runspace runspace = RunspaceFactory.CreateRunspace(/*myHost,*/ iss)) { runspace.Open(); using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspace; powerShell.AddScript("Import-Module Microsoft.PowerShell.Utility -Force"); powerShell.AddScript(script); int objCount = 0; var results = powerShell.Invoke(); foreach (var result in results) { // this is how an object would be captured here and looked at, // each result is a PSObject with the data from the pipeline ++objCount; Assert.NotNull(result); } Assert.Equal(count, objCount); powerShell.Dispose(); } } }
//Get reports public string GetPowerBIReport() { // Create the InitialSessionState Object InitialSessionState iss = InitialSessionState.CreateDefault2(); // Initialize PowerShell Engine var shell = PowerShell.Create(iss); shell.Commands.AddCommand("Connect-PowerBIServiceAccount"); //shell.Commands.AddCommand("Get-PowerBIWorkspace"); var userName = "******"; var pwd = "Dac21568"; System.Security.SecureString theSecureString = new NetworkCredential(userName, pwd).SecurePassword; PSCredential cred = new PSCredential(userName, theSecureString); shell.Commands.AddParameter("Credential", cred); var builder = new StringBuilder(); // Execute the script try { var results = shell.Invoke(); // display results, with BaseObject converted to string // Note : use |out-string for console-like output if (results.Count > 0) { // We use a string builder to create our result text //var builder = new StringBuilder(); var shell1 = PowerShell.Create(iss); shell1.Commands.AddCommand("Get-PowerBIReport"); shell1.Commands.AddParameter("WorkspaceId", "ea5ec2c2-def9-4b74-9133-305511d96fdf"); var res = shell1.Invoke(); if (res.Count > 0) { foreach (var psObject in res) { // Convert the Base Object to a string and append it to the string builder. // Add \r\n for line breaks var reportName = psObject.Properties["Name"].Value; builder.Append(psObject.Properties["Name"].Value + "\r\n"); //builder.Append(psObject.BaseObject.ToString()); } //ReportResult.Text = Server.HtmlEncode(builder.ToString()); } } } catch (ActionPreferenceStopException Error) { //DatasetResult.Text = Error.Message; } catch (RuntimeException Error) { //DatasetResult.Text = Error.Message; }; return(HttpUtility.HtmlEncode(builder.ToString())); }
public List <ExternalRule> GetExternalRule(string[] moduleNames) { List <ExternalRule> rules = new List <ExternalRule>(); if (moduleNames == null) { return(rules); } // Converts module path to module name. foreach (string moduleName in moduleNames) { string shortModuleName = string.Empty; // Imports modules by using full path. InitialSessionState state = InitialSessionState.CreateDefault2(); state.ImportPSModule(new string[] { moduleName }); using (System.Management.Automation.PowerShell posh = System.Management.Automation.PowerShell.Create(state)) { string script = string.Format(CultureInfo.CurrentCulture, "Get-Module -Name '{0}' -ListAvailable", moduleName); shortModuleName = posh.AddScript(script).Invoke <PSModuleInfo>().First().Name; // Invokes Update-Help for this module // Required since when invoking Get-Help later on, the cmdlet prompts for Update-Help interactively // By invoking Update-Help first, Get-Help will not prompt for downloading help later script = string.Format(CultureInfo.CurrentCulture, "Update-Help -Module '{0}' -Force", shortModuleName); posh.AddScript(script).Invoke(); // Invokes Get-Command and Get-Help for each functions in the module. script = string.Format(CultureInfo.CurrentCulture, "Get-Command -Module '{0}'", shortModuleName); var psobjects = posh.AddScript(script).Invoke(); foreach (PSObject psobject in psobjects) { posh.Commands.Clear(); FunctionInfo funcInfo = (FunctionInfo)psobject.ImmediateBaseObject; ParameterMetadata param = funcInfo.Parameters.Values .First <ParameterMetadata>(item => item.Name.EndsWith("ast", StringComparison.OrdinalIgnoreCase) || item.Name.EndsWith("token", StringComparison.OrdinalIgnoreCase)); //Only add functions that are defined as rules. if (param != null) { script = string.Format(CultureInfo.CurrentCulture, "(Get-Help -Name {0}).Description | Out-String", funcInfo.Name); string desc = posh.AddScript(script).Invoke()[0].ImmediateBaseObject.ToString() .Replace("\r\n", " ").Trim(); rules.Add(new ExternalRule(funcInfo.Name, funcInfo.Name, desc, param.Name, param.ParameterType.FullName, funcInfo.ModuleName, funcInfo.Module.Path)); } } } } return(rules); }
private static InitialSessionState GetSessionState(SessionState sessionState) { var initialSessionState = InitialSessionState.CreateDefault2(); CaptureVariables(sessionState, initialSessionState); CaptureFunctions(sessionState, initialSessionState); return(initialSessionState); }
public static int Start(string?bannerText, string?helpText, string[] args) { return(StartImpl( initialSessionState: InitialSessionState.CreateDefault2(), bannerText, helpText, args, issProvided: false)); }
public static PowerShell CreateWithImportedModules(params string[] modules) { Environment.SetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT", "true"); var sessionState = InitialSessionState.CreateDefault2(); sessionState.ThreadOptions = PSThreadOptions.UseCurrentThread; sessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted; sessionState.ImportPSModule(modules); return(PowerShell.Create(sessionState)); }
private ExecutionContext GetExecutionContext() { CultureInfo currentCulture = CultureInfo.CurrentCulture; PSHost hostInterface = new DefaultHost(currentCulture, currentCulture); InitialSessionState iss = InitialSessionState.CreateDefault2(); AutomationEngine engine = new AutomationEngine(hostInterface, iss); ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss); return(executionContext); }
/// <summary> /// Create a new runspace pool around a PSScriptAnalyzer module for asynchronous script analysis tasks. /// This looks for the latest version of PSScriptAnalyzer on the path and loads that. /// </summary> /// <returns>A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks.</returns> private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo) { using (var ps = System.Management.Automation.PowerShell.Create()) { // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"` ps.AddCommand("Get-Module") .AddParameter("ListAvailable") .AddParameter("Name", PSSA_MODULE_NAME); try { using (PSModulePathPreserver.Take()) { // Get the latest version of PSScriptAnalyzer we can find pssaModuleInfo = ps.Invoke <PSModuleInfo>()? .OrderByDescending(moduleInfo => moduleInfo.Version) .FirstOrDefault(); } } catch (Exception e) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e); } if (pssaModuleInfo == null) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path"); } // Now that we know where the PSScriptAnalyzer we want to use is, // create a base session state with PSScriptAnalyzer loaded #if DEBUG InitialSessionState sessionState = Environment.GetEnvironmentVariable("PSES_TEST_USE_CREATE_DEFAULT") == "1" ? InitialSessionState.CreateDefault() : InitialSessionState.CreateDefault2(); #else InitialSessionState sessionState = InitialSessionState.CreateDefault2(); #endif sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase }); RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState); runspacePool.SetMaxRunspaces(1); runspacePool.ThreadOptions = PSThreadOptions.ReuseThread; // Open the runspace pool here so we can deterministically handle the PSModulePath change issue using (PSModulePathPreserver.Take()) { runspacePool.Open(); } return(runspacePool); } }
private static void InitPowerShell() { s_ps = System.Management.Automation.PowerShell.Create(InitialSessionState.CreateDefault2()); s_ps.AddScript("$PSHOME"); //s_ps.AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", ExecutionPolicy.Unrestricted).AddParameter("Scope", ExecutionPolicyScope.Process); var result = s_ps.Invoke <string>(); s_ps.Commands.Clear(); Console.WriteLine(result[0]); }
/// <summary> /// Starts a job as defined by the contained ScheduledJobDefinition object. /// </summary> public override void StartJob() { lock (SyncRoot) { if (_job != null && !IsFinishedState(_job.JobStateInfo.State)) { string msg = StringUtil.Format(ScheduledJobErrorStrings.JobAlreadyRunning, _jobDefinition.Name); throw new PSInvalidOperationException(msg); } _statusInfo = null; _asyncJobStop = false; PSBeginTime = DateTime.Now; if (_powerShell == null) { InitialSessionState iss = InitialSessionState.CreateDefault2(); iss.Commands.Clear(); iss.Formats.Clear(); iss.Commands.Add( new SessionStateCmdletEntry("Start-Job", typeof(Microsoft.PowerShell.Commands.StartJobCommand), null)); // Get the default host from the default runspace. _host = GetDefaultHost(); _runspace = RunspaceFactory.CreateRunspace(_host, iss); _runspace.Open(); _powerShell = System.Management.Automation.PowerShell.Create(); _powerShell.Runspace = _runspace; // Indicate SetShouldExit to host. AddSetShouldExitToHost(); } else { _powerShell.Commands.Clear(); } _job = StartJobCommand(_powerShell); _job.StateChanged += new EventHandler <JobStateEventArgs>(HandleJobStateChanged); SetJobState(_job.JobStateInfo.State); // Add all child jobs to this object's list so that // the user and Receive-Job can retrieve results. foreach (Job childJob in _job.ChildJobs) { this.ChildJobs.Add(childJob); } // Add this job to the local repository. ScheduledJobSourceAdapter.AddToRepository(this); } // lock }
public void TestDrives() { CultureInfo currentCulture = CultureInfo.CurrentCulture; PSHost hostInterface = new DefaultHost(currentCulture, currentCulture); InitialSessionState iss = InitialSessionState.CreateDefault2(); AutomationEngine engine = new AutomationEngine(hostInterface, iss); ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss); SessionStateInternal sessionState = new SessionStateInternal(executionContext); Collection <PSDriveInfo> drives = sessionState.Drives(null); Assert.NotNull(drives); }
public string NewPowerBIWorkspace() { InitialSessionState iss = InitialSessionState.CreateDefault2(); var shell2 = PowerShell.Create(iss); shell2.Commands.AddCommand("New-PowerBIWorkspace"); shell2.Commands.AddParameter("Name", "New Workspace"); var resNewWorkspace = shell2.Invoke(); return("New Workspace Created Successfully."); }
public string GetPowerBIWorkspaceMigrationStatus() { InitialSessionState iss = InitialSessionState.CreateDefault2(); var shell2 = PowerShell.Create(iss); shell2.Commands.AddCommand("Get-PowerBIWorkspaceMigrationStatus"); shell2.Commands.AddParameter("Id", "ea5ec2c2-def9-4b74-9133-305511d96fdf"); var resMigrationStatus = shell2.Invoke(); return("Migration status"); }
static void Main() { //Box(new List<string> {"abc", " def", "this is something coo"}); var iss = InitialSessionState.CreateDefault2(); var rs = RunspaceFactory.CreateRunspace(iss); rs.Open(); Runspace.DefaultRunspace = rs; PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Emacs, }); //PSConsoleReadLine.SetKeyHandler(new[] {"UpArrow"}, PSConsoleReadLine.HistorySearchBackward, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"DownArrow"}, PSConsoleReadLine.HistorySearchForward, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+E"}, PSConsoleReadLine.EnableDemoMode, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+D"}, PSConsoleReadLine.DisableDemoMode, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+C"}, PSConsoleReadLine.CaptureScreen, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+D,Ctrl+P" }, PSConsoleReadLine.InvokePrompt, "", ""); while (true) { //Console.Write("C:\\Windows\nPS> "); Console.Write("PS> "); var line = PSConsoleReadLine.ReadLine(); Console.WriteLine(line); line = line.Trim(); if (line.Equals("exit")) { Environment.Exit(0); } if (line.Equals("cmd")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Windows }); } if (line.Equals("emacs")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Emacs }); } if (line.Equals("nodupes")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { HistoryNoDuplicates = true }); } } }
/// <summary> /// Create a new runspace pool around a PSScriptAnalyzer module for asynchronous script analysis tasks. /// This looks for the latest version of PSScriptAnalyzer on the path and loads that. /// </summary> /// <returns>A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks.</returns> private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo) { using (var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace)) { // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"` ps.AddCommand("Get-Module") .AddParameter("ListAvailable") .AddParameter("Name", PSSA_MODULE_NAME); try { using (PSModulePathPreserver.Take()) { // Get the latest version of PSScriptAnalyzer we can find pssaModuleInfo = ps.Invoke <PSModuleInfo>()? .OrderByDescending(moduleInfo => moduleInfo.Version) .FirstOrDefault(); } } catch (Exception e) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e); } if (pssaModuleInfo == null) { throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path"); } // Now that we know where the PSScriptAnalyzer we want to use is, create a base // session state with PSScriptAnalyzer loaded // // We intentionally use `CreateDefault2()` as it loads `Microsoft.PowerShell.Core` // only, which is a more minimal and therefore safer state. InitialSessionState sessionState = InitialSessionState.CreateDefault2(); sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase }); RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState); runspacePool.SetMaxRunspaces(1); runspacePool.ThreadOptions = PSThreadOptions.ReuseThread; // Open the runspace pool here so we can deterministically handle the PSModulePath change issue using (PSModulePathPreserver.Take()) { runspacePool.Open(); } return(runspacePool); } }
/// <summary> /// Gets a new minimal runspace. /// </summary> public static Runspace GetMinimalRunspace() { // Create a mini runspace by remove the types and formats InitialSessionState minimalState = InitialSessionState.CreateDefault2(); // Refer to the remarks for the property DefaultRunspace. minimalState.Types.Clear(); minimalState.Formats.Clear(); var runspace = RunspaceFactory.CreateRunspace(minimalState); runspace.Open(); return(runspace); }
/// <summary> /// Initializes a new instance of the <see cref="RunspaceFixture"/> class. /// </summary> public RunspaceFixture() { host = new TestableHost(); var state = InitialSessionState.CreateDefault2(); state.AuthorizationManager = null; state.LanguageMode = PSLanguageMode.RestrictedLanguage; state.ImportPSModule(new[] { @".\RestartManager.psd1" }); runspace = RunspaceFactory.CreateRunspace(host, state); runspace.Open(); }
public PowershellEngine() { var iss = InitialSessionState.CreateDefault2(); _runspace = RunspaceFactory.CreateRunspacePool(iss); _runspace.Open(); using (var ps = CreateShell()) { ps.AddScript("import-module Hyper-V -RequiredVersion 1.1"); ps.Invoke(); } }
//run all fixes private void AllClicked(object sender, RoutedEventArgs e) { using (var PowerShellInstance = PowerShell.Create(InitialSessionState.CreateDefault2())) { PowerShellInstance.AddScript( "netsh wlan delete profile name='ChargerWifi';" + "netsh wlan delete profile name='ChargerGuest - STS';" + "netsh wlan delete profile name='UNHStudent';" + "netsh wlan delete profile name='UNH';" + "netsh wlan delete profile name='OITBroadband';" + "netsh wlan delete profile name='ChargerGuest';" + "netsh wlan delete profile name='Devices';" + "netsh wlan delete profile name='FH*';" + "netsh wlan delete profile name='MS*'; " + "powercfg /hibernate off; " + "ipconfig /flushdns; " + "ForEach ($NIC in (Get-NetAdapter -Physical)){;" + "$PowerSaving = Get-CimInstance -ClassName MSPower_DeviceEnable -Namespace root\\wmi | ? {$_.InstanceName -match [Regex]::Escape($NIC.PnPDeviceID)};" + "If ($PowerSaving.Enable){ $PowerSaving.Enable = $false; $PowerSaving | Set-CimInstance } }" + "Disable-NetAdapter -InterfaceDescription 'WAN Miniport*' -IncludeHidden -Confirm:$false;" + "Set-ItemProperty -Path HKLM:\\SOFTWARE\\Microsoft\\WlanSvc\\AnqpCache -Name OsuRegistrationStatus -Value 0;" + "netsh winsock reset;" + "netsh int ip reset;" + "netsh int tcp reset;" + "$WiFi = Get-NetAdapter -Name '*Wi-Fi*';" + "$RegPath = 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}';" + "($Key = Get-ItemProperty -Path $RegPath\\* -Name AdapterModel) 2> $Null;" + "If($Key.AdapterModel -eq $WiFi.InterfaceDescription){;" + "New-ItemProperty -Path $RegPath\\$($Key.PSChildName) -Name NetworkAddress -Value $($WiFi.MacAddress) -PropertyType String -Force}" ); var result = PowerShellInstance.BeginInvoke(); while (result.IsCompleted == false) { Thread.Sleep(1000); } /* * using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) * using (var key = hklm.OpenSubKey("SOFTWARE\\Microsoft\\WlanSvc\\AnqpCache", true)) * { * if (key != null) //must check for null key * { * key.SetValue("OsuRegistrationStatus", 0); * } * } */ MessageBox.Show("All Actions Finished\n\n" + "Please restart your computer to complete the process", "Process Complete"); } }