Example #1
0
        internal RequestProcessor(MessagingStream msgStream, System.Management.Automation.PowerShell firstPwshInstance)
        {
            _msgStream         = msgStream;
            _firstPwshInstance = firstPwshInstance;
            _powershellPool    = new PowerShellManagerPool(() => new RpcLogger(msgStream));

            // Host sends capabilities/init data to worker
            _requestHandlers.Add(StreamingMessage.ContentOneofCase.WorkerInitRequest, ProcessWorkerInitRequest);

            // Host sends terminate message to worker.
            // Worker terminates if it can, otherwise host terminates after a grace period
            _requestHandlers.Add(StreamingMessage.ContentOneofCase.WorkerTerminate, ProcessWorkerTerminateRequest);

            // Add any worker relevant status to response
            _requestHandlers.Add(StreamingMessage.ContentOneofCase.WorkerStatusRequest, ProcessWorkerStatusRequest);

            // On file change event, host sends notification to worker
            _requestHandlers.Add(StreamingMessage.ContentOneofCase.FileChangeEventRequest, ProcessFileChangeEventRequest);

            // Host sends required metadata to worker to load function
            _requestHandlers.Add(StreamingMessage.ContentOneofCase.FunctionLoadRequest, ProcessFunctionLoadRequest);

            // Host requests a given invocation
            _requestHandlers.Add(StreamingMessage.ContentOneofCase.InvocationRequest, ProcessInvocationRequest);

            // Host sends cancel message to attempt to cancel an invocation.
            // If an invocation is cancelled, host will receive an invocation response with status cancelled.
            _requestHandlers.Add(StreamingMessage.ContentOneofCase.InvocationCancel, ProcessInvocationCancelRequest);

            _requestHandlers.Add(StreamingMessage.ContentOneofCase.FunctionEnvironmentReloadRequest, ProcessFunctionEnvironmentReloadRequest);
        }
Example #2
0
        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/");
        }
Example #3
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 #4
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 #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
 /// <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 static Cmdlet  CreateCmdlet(Runspace rss)
        {
            var cmdlet = Cmdlet.Create();

            cmdlet.Runspace = rss;
            return(cmdlet);
        }
Example #8
0
 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");
     }
 }
Example #9
0
 internal override System.Management.Automation.PowerShell GetPowerShell(
     Guid instanceId)
 {
     System.Management.Automation.PowerShell powerShell = (System.Management.Automation.PowerShell)null;
     this.powershells.TryGetValue(instanceId, out powerShell);
     return(powerShell);
 }
Example #10
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 #11
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);
 }
        private static void CheckErrors(System.Management.Automation.PowerShell powerShellInstance)
        {
            var exceptions = powerShellInstance.Streams.Error.Select(error => error.Exception).ToList();

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
Example #13
0
 internal RemotePipeline(RemoteRunspace runspace, string command, bool addToHistory, bool isNested) : this(runspace, addToHistory, isNested)
 {
     if (command != null)
     {
         this._commands.Add(new Command(command, true));
     }
     this._powershell = new System.Management.Automation.PowerShell(this._inputStream, this._outputStream, this._errorStream, ((RemoteRunspace)this._runspace).RunspacePool);
     this._powershell.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(this.HandleInvocationStateChanged);
 }
Example #14
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);
        }
 public void CleanUp()
 {
     // Make sure we cleanup everything
     this.PowerShell.Dispose();
     this.Invoker.Dispose();
     this.RunSpace.Close();
     this.Invoker = null;
     this.RunSpace = null;
     this.SessionState = null;
     this.PowerShell = null;
 }
Example #16
0
 public void CleanUp()
 {
     // Make sure we cleanup everything
     this.PowerShell.Dispose();
     this.Invoker.Dispose();
     this.RunSpace.Close();
     this.Invoker      = null;
     this.RunSpace     = null;
     this.SessionState = null;
     this.PowerShell   = null;
 }
 /// <summary>
 /// Executes PowerShell command.
 /// </summary>
 /// <param name="command">PowerShell command to be executed.</param>
 public void Execute(string command)
 {
     using (var ps = PowerShell.Create())
     {
         var results = ps.AddScript(command).Invoke();
         foreach (var result in results)
         {
             this.logger.LogDebug(result.ToString());
         }
     }
 }
Example #18
0
        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (GetIsComputerNameSpecified(context))
            {
                targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
            }

            if (Authentication.Expression != null)
            {
                targetCommand.AddParameter("Authentication", Authentication.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }

            if (CertificateThumbprint.Expression != null)
            {
                targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (OperationTimeoutSec.Expression != null)
            {
                targetCommand.AddParameter("OperationTimeoutSec", OperationTimeoutSec.Get(context));
            }

            if (Port.Expression != null)
            {
                targetCommand.AddParameter("Port", Port.Get(context));
            }

            if (SessionOption.Expression != null)
            {
                targetCommand.AddParameter("SessionOption", SessionOption.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Example #19
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 #20
0
 internal RemotePipeline(RemoteRunspace runspace) : this(runspace, false, false)
 {
     if (runspace.RemoteCommand == null)
     {
         throw new InvalidOperationException(PipelineStrings.InvalidRemoteCommand);
     }
     this._connectCmdInfo = runspace.RemoteCommand;
     this._commands.Add(this._connectCmdInfo.Command);
     this.SetPipelineState(PipelineState.Disconnected, null);
     this._powershell = new System.Management.Automation.PowerShell(this._connectCmdInfo, this._inputStream, this._outputStream, this._errorStream, ((RemoteRunspace) this._runspace).RunspacePool);
     this._powershell.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(this.HandleInvocationStateChanged);
 }
Example #21
0
 internal RemotePipeline(RemoteRunspace runspace) : this(runspace, false, false)
 {
     if (runspace.RemoteCommand == null)
     {
         throw new InvalidOperationException(PipelineStrings.InvalidRemoteCommand);
     }
     this._connectCmdInfo = runspace.RemoteCommand;
     this._commands.Add(this._connectCmdInfo.Command);
     this.SetPipelineState(PipelineState.Disconnected, null);
     this._powershell = new System.Management.Automation.PowerShell(this._connectCmdInfo, this._inputStream, this._outputStream, this._errorStream, ((RemoteRunspace)this._runspace).RunspacePool);
     this._powershell.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(this.HandleInvocationStateChanged);
 }
        // Additional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Namespace.Expression != null)
            {
                targetCommand.AddParameter("Namespace", Namespace.Get(context));
            }

            if (OperationTimeoutSec.Expression != null)
            {
                targetCommand.AddParameter("OperationTimeoutSec", OperationTimeoutSec.Get(context));
            }

            if (InputObject.Expression != null)
            {
                targetCommand.AddParameter("InputObject", InputObject.Get(context));
            }

            if (Query.Expression != null)
            {
                targetCommand.AddParameter("Query", Query.Get(context));
            }

            if (QueryDialect.Expression != null)
            {
                targetCommand.AddParameter("QueryDialect", QueryDialect.Get(context));
            }

            if (Property.Expression != null)
            {
                targetCommand.AddParameter("Property", Property.Get(context));
            }

            if (PassThru.Expression != null)
            {
                targetCommand.AddParameter("PassThru", PassThru.Get(context));
            }

            if (ResourceUri != null)
            {
                targetCommand.AddParameter("ResourceUri", ResourceUri.Get(context));
            }

            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Example #23
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 #24
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();
        }
Example #25
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);
        }
Example #26
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 #27
0
        private void RunService()
        {
            InitialSessionState initalState   = InitialSessionState.CreateDefault();
            List <string>       modulesToLoad = Common.ProcessManifest(initalState);

            lock (psLocker)
            {
                powershellHost   = new Host();
                powershellEngine = System.Management.Automation.PowerShell.Create();

                powershellEngine.Runspace = RunspaceFactory.CreateRunspace(powershellHost, initalState);
                powershellEngine.Runspace.ApartmentState = System.Threading.ApartmentState.MTA;
                powershellEngine.Runspace.Open();
            }

            try
            {
                RunScript("Set-ExecutionPolicy Unrestricted -Scope Process");
            }
            catch
            {
            }


            foreach (string module in modulesToLoad)
            {
                try
                {
                    RunScript(string.Format("Import-Module {0} -Scope Global", module));
                }
                catch (Exception e)
                {
                    EventLog.WriteEntry(PSService.PSServiceName, string.Format("Error occured while initializing modules.{0}{0}Name: {1}{0}Error: {2}", Environment.NewLine, module, e.Message), EventLogEntryType.Error);
                }
            }

            RunScript(Common.GetScript("ScriptData"));
            RunScript("if (Get-Command OnStart -ea SilentlyContinue) { OnStart }");
            RunScript("Main");

            lock (psLocker)
            {
                powershellEngine.Dispose();
                powershellEngine = null;
            }

            thread.Abort();
            thread.Join();

            Common.CleanUp();
        }
Example #28
0
        public PowerShell(IConsoleLogger consoleLogger)
        {
            this.consoleLogger = consoleLogger;

            runspace   = RunspaceFactory.CreateRunspace();
            powershell = System.Management.Automation.PowerShell.Create(runspace);
            runspace.Open();

            powershell.Streams.Debug.DataAdded       += DebugDataAdded;
            powershell.Streams.Verbose.DataAdded     += VerboseDataAdded;
            powershell.Streams.Information.DataAdded += InformationDataAdded;
            powershell.Streams.Warning.DataAdded     += WarningDataAdded;
            powershell.Streams.Error.DataAdded       += ErrorDataAdded;
            powershell.Streams.Progress.DataAdded    += ProgressDataAdded;
        }
        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"));
        }
        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 #31
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();
        }
 /// <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;
         }
     }
 }
        public PowerShellTestsSession()
        {
            this.SessionState = System.Management.Automation.Runspaces.InitialSessionState.CreateDefault();


            // Get path of where everything is executing so we can find the VisioPS.dll assembly
            var executing_assembly = System.Reflection.Assembly.GetExecutingAssembly();
            var asm_path = System.IO.Path.GetDirectoryName(executing_assembly.GetName().CodeBase);
            var uri = new System.Uri(asm_path);
            var visio_ps = System.IO.Path.Combine(uri.LocalPath, "VisioPS.dll");
            var modules = new[] { visio_ps };

            // Import the latest VisioPS module into the PowerShell session
            this.SessionState.ImportPSModule(modules);
            this.RunSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(this.SessionState);
            this.RunSpace.Open();
            this.PowerShell = System.Management.Automation.PowerShell.Create();
            this.PowerShell.Runspace = this.RunSpace;
            this.Invoker = new System.Management.Automation.RunspaceInvoke(this.RunSpace);
        }
Example #34
0
 internal RemotePipeline(RemoteRunspace runspace, string command, bool addToHistory, bool isNested) : this(runspace, addToHistory, isNested)
 {
     if (command != null)
     {
         this._commands.Add(new Command(command, true));
     }
     this._powershell = new System.Management.Automation.PowerShell(this._inputStream, this._outputStream, this._errorStream, ((RemoteRunspace) this._runspace).RunspacePool);
     this._powershell.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(this.HandleInvocationStateChanged);
 }
Example #35
0
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (!this._disposed)
         {
             lock (this._syncRoot)
             {
                 if (this._disposed)
                 {
                     return;
                 }
                 this._disposed = true;
             }
             if (disposing)
             {
                 this.Stop();
                 if (this._powershell != null)
                 {
                     this._powershell.Dispose();
                     this._powershell = null;
                 }
                 this._inputCollection.Dispose();
                 this._inputStream.Dispose();
                 this._outputCollection.Dispose();
                 this._outputStream.Dispose();
                 this._errorCollection.Dispose();
                 this._errorStream.Dispose();
                 this._methodExecutorStream.Dispose();
                 this._pipelineFinishedEvent.Close();
             }
         }
     }
     finally
     {
         base.Dispose(disposing);
     }
 }