{
	"id": "292eabdb-1b29-4596-8dbf-3a0a727bb357",
	"created_at": "2026-04-06T00:20:18.053803Z",
	"updated_at": "2026-04-10T03:21:38.853594Z",
	"deleted_at": null,
	"sha1_hash": "dfd5644684109d0c133c84e6ea203bdad2ccafea",
	"title": "Executing PowerShell scripts from C#",
	"llm_title": "",
	"authors": "",
	"file_creation_date": "0001-01-01T00:00:00Z",
	"file_modification_date": "0001-01-01T00:00:00Z",
	"file_size": 173124,
	"plain_text": "Executing PowerShell scripts from C#\r\nBy kexugit\r\nArchived: 2026-04-05 22:04:26 UTC\r\nIn today’s post, I will demonstrate the basics of how to execute PowerShell scripts and code from within a\r\nC#/.NET applications. I will walk through how to setup your project prerequisites, populate the pipeline with\r\nscript code and parameters, perform synchronous and asynchronous execution, capture output, and leverage\r\nshared namespaces.\r\nUpdate 8/7/2014: Here is the downloadable solution file.\r\nUpdate 11/5/2014: Added a section on execution policy behavior.\r\nPrerequisites:\r\nFirst, ensure that PowerShell 2.0 or later is installed on the system you are developing on. The features used below\r\nwill not be supported on PowerShell 1.0. Next, start by making a new console application (targeting .NET 4.0) in\r\nVisual Studio.\r\nIn the solution explorer, add a project reference to the System.Management.Automation assembly * . On my\r\nmachine (PowerShell 3.0), it was located at C:\\Program Files (x86)\\Reference\r\nAssemblies\\Microsoft\\WindowsPowerShell\\3.0. Then, add using statements for the above referenced assembly,\r\nalong with System.Collections.Objectmodel, which is used later for execution output.\r\nNote: You will need to install the Windows SDK in order to obtain the System.Management.Automation assembly\r\nfile.\r\nNote: You do not have to distribute the System.Management.Automation assembly file with your application\r\nbinaries - it is located in the GAC on machines with Windows PowerShell installed and should resolve\r\nautomatically.\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 1 of 16\n\nPrepare the Pipeline for execution:\r\nThe first step is to create a new instance of the PowerShell class. The static method PowerShell.Create() creates\r\nan empty PowerShell pipeline for us to use for execution. The PowerShell class implements IDisposable, so\r\nremember to wrap it up in a using block.\r\n using(PowerShellPowerShellInstance=PowerShell.Create())\r\n{\r\n}\r\nNext, we can add scripts or commands to execute. Call the AddScript() and AddCommand() methods to add this\r\ncontent to the execution pipeline. If your script has parameters, adding them is easy with the AddParameter()\r\nmethod. AddParameter() accepts a string parameter name, and object for the parameter value. Feel free to pass in\r\nfull object instances/types if you want. The scripts and pipeline handle it just fine. No need to limit yourself with\r\nonly passing in string values.\r\nThe string contents supplied to AddScript() can come from anywhere. Good choices may be text loaded from files\r\non disk or embedded resources, or user input. For the purposes of this tutorial, I’m just hard-coding some example\r\nscript text.\r\n using(PowerShellPowerShellInstance=PowerShell.Create())\r\n{\r\n// use \"AddScript\" to add the contents of a script file to the end of the execution pipeline.\r\n// use \"AddCommand\" to add individual commands/cmdlets to the end of the execution pipeline.\r\nPowerShellInstance.AddScript(\"param($param1) $d = get-date; $s = 'test string value'; \"+\r\n\"$d; $s; $param1; get-service\");\r\n // use \"AddParameter\" to add a single parameter to the last command/script on the pipeline.\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 2 of 16\n\nPowerShellInstance.AddParameter(\"param1\",\"parameter 1 value!\");\r\n}\r\nScript/Command Execution:\r\nSo far, we have a PowerShell pipeline populated with script code and parameters. There are two ways we can call\r\nPowerShell to execute it: synchronously and asynchronously.\r\nSynchronous execution:\r\nFor synchronous execution, we call PowerShell.Invoke() . The caller waits until the script or commands have\r\nfinished executing completely before returning from the call to Invoke() . If you don’t care about the items in the\r\noutput stream, the simplest execution looks like this:\r\n // invoke execution on the pipeline (ignore output)\r\nPowerShellInstance.Invoke();\r\nFor situations where you don’t need to see or monitor the output or results of execution, this may be acceptable.\r\nBut, in other scenarios you probably need to peek at the results or perform additional processing with the output\r\nthat comes back from PowerShell. Let’s see what that code looks like:\r\n // invoke execution on the pipeline (collecting output)\r\nCollection\u003cPSObject\u003ePSOutput=PowerShellInstance.Invoke();\r\n// loop through each output object item\r\nforeach(PSObjectoutputIteminPSOutput)\r\n{\r\n// if null object was dumped to the pipeline during the script then a null\r\n// object may be present here. check for null to prevent potential NRE.\r\nif(outputItem!=null)\r\n{\r\n//TODO: do something with the output item\r\n// outputItem.BaseOBject\r\n}\r\n}\r\nThe return object from Invoke() is a collection of PSObject instances that were written to the output stream during\r\nexecution. PSObject is a wrapper class that adds PowerShell specific functionality around whatever the base\r\nobject is. Inside the PSObject is a member called BaseObject, which contains an object reference to the base type\r\nyou are working with. If nothing was written to the output stream, then the collection of PSObjects will be empty.\r\nBesides the standard output stream, there are also dedicated streams for warnings, errors, debug, progress, and\r\nverbose logging. If any cmdlets leverage those streams, or you call them directly (write-error, write-debug, etc.),\r\nthen those items will appear in the streams collections.\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 3 of 16\n\nAfter invoking the script, you can check each of these stream collections to see if items were written to them.\r\n // invoke execution on the pipeline (collecting output)\r\nCollection\u003cPSObject\u003ePSOutput=PowerShellInstance.Invoke();\r\n // check the other output streams (for example, the error stream)\r\nif(PowerShellInstance.Streams.Error.Count\u003e0)\r\n{\r\n// error records were written to the error stream.\r\n// do something with the items found.\r\n}\r\nIn my sample script supplied above, I am writing a few manually-created objects to the output stream and calling\r\nthe get-service cmdlet, which also writes its output to the stream since I didn’t save the output in a variable.\r\nAs a test, I write the type name and ToString() on all of the base objects that came back from the sample script. As\r\nyou can see, accessing the base object allows you to view or manipulate the object directly as needed. The base\r\ntypes that come back from execution are usually standard .NET types you may already be familiar with, just\r\nwrapped up in a PSObject.\r\n // loop through each output object item\r\nforeach(PSObjectoutputIteminPSOutput)\r\n{\r\n// if null object was dumped to the pipeline during the script then a null\r\n// object may be present here. check for null to prevent potential NRE.\r\nif(outputItem!=null)\r\n{\r\n//TODO: do something with the output item\r\nConsole.WriteLine(outputItem.BaseObject.GetType().FullName);\r\nConsole.WriteLine(outputItem.BaseObject.ToString()+\"\\n\");\r\n}\r\n}\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 4 of 16\n\nAsynchronous execution:\r\nFor asynchronous execution, we call PowerShell.BeginInvoke() . BeginInvoke() immediately returns to the caller\r\nand the script execution begins in the background so you can perform other work. Unlike the synchronous\r\nInvoke() method, the return type of BeginInvoke() is not a collection of PSObject instances from the output\r\nstream. The output isn’t ready yet. The caller is given an IAsyncResult object to monitor the status of the\r\nexecution pipeline. Let’s start with a really simple example:\r\n using(PowerShellPowerShellInstance=PowerShell.Create())\r\n{\r\n// this script has a sleep in it to simulate a long running script\r\nPowerShellInstance.AddScript(\"start-sleep -s 7; get-service\");\r\n// begin invoke execution on the pipeline\r\nIAsyncResultresult=PowerShellInstance.BeginInvoke();\r\n// do something else until execution has completed.\r\n// this could be sleep/wait, or perhaps some other work\r\nwhile(result.IsCompleted==false)\r\n{\r\nConsole.WriteLine(\"Waiting for pipeline to finish...\");\r\nThread.Sleep(1000);\r\n// might want to place a timeout here...\r\n}\r\nConsole.WriteLine(\"Finished!\");\r\n}\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 5 of 16\n\nNote: If you wrap the PowerShell instance in a using block like the sample above and do not wait for execution to\r\ncomplete, the pipeline will close itself, and will abort script execution, when it reaches the closing brace of the\r\nusing block. You can avoid this by waiting for completion of the pipeline, or by removing the using block and\r\nmanually calling Dispose() on the instance at a later time.\r\nIn this first asynchronous example, we ignored the output stream. Again, this is only useful if you don’t care about\r\nyour script results. Fortunately, the BeginInvoke() method has a few overloads that allow us to extend the\r\nfunctionality. Let’s improve the example by adding output collection and event handling for data hitting the\r\npipeline.\r\nFirst, we will create a new instance of PSDataCollection\u003cPSObject\u003e . This collection is a thread-safe buffer that\r\nwill store output stream objects as they hit the pipeline. Next, we will subscribe to the DataAdded event on this\r\ncollection. This event will fire every time an object is written to the output stream. To use this new output buffer,\r\npass it as a parameter to BeginInvoke() .\r\nI added some other functionality and comments to the next code block. First, notice that you can check the state of\r\nthe pipeline to see its status. The State will equal Completed when your script is done. If State is Failed, it is\r\nlikely caused by an unhandled exception that occurred in the script, also known as a terminating error. Second, if\r\nyour scripts utilize write-error, write-debug, write-progress, etc. (all thread-safe collections), you can review\r\nthese during or after execution to check for items logged there. I have subscribed to the DataAdded event on the\r\nError stream as well to be notified in real time.\r\n ///\u003csummary\u003e\r\n///Sample execution scenario 2: Asynchronous\r\n///\u003c/summary\u003e\r\n///\u003cremarks\u003e\r\n///Executes a PowerShell script asynchronously with script output and event handling.\r\n///\u003c/remarks\u003e\r\npublicvoidExecuteAsynchronously()\r\n{\r\nusing(PowerShellPowerShellInstance=PowerShell.Create())\r\n{\r\n// this script has a sleep in it to simulate a long running script\r\nPowerShellInstance.AddScript(\"$s1 = 'test1'; $s2 = 'test2'; $s1; write-error 'some error';start-slee\r\n// prepare a new collection to store output stream objects\r\nPSDataCollection\u003cPSObject\u003eoutputCollection=newPSDataCollection\u003cPSObject\u003e();\r\noutputCollection.DataAdded+=outputCollection_DataAdded;\r\n// the streams (Error, Debug, Progress, etc) are available on the PowerShell instance.\r\n// we can review them during or after execution.\r\n// we can also be notified when a new item is written to the stream (like this):\r\nPowerShellInstance.Streams.Error.DataAdded+=Error_DataAdded;\r\n// begin invoke execution on the pipeline\r\n// use this overload to specify an output stream buffer\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 6 of 16\n\nIAsyncResultresult=PowerShellInstance.BeginInvoke\u003cPSObject,PSObject\u003e(null,outputCollection);\r\n// do something else until execution has completed.\r\n// this could be sleep/wait, or perhaps some other work\r\nwhile(result.IsCompleted==false)\r\n{\r\nConsole.WriteLine(\"Waiting for pipeline to finish...\");\r\nThread.Sleep(1000);\r\n// might want to place a timeout here...\r\n}\r\nConsole.WriteLine(\"Execution has stopped. The pipeline state: \"+PowerShellInstance.InvocationState\r\nforeach(PSObjectoutputIteminoutputCollection)\r\n{\r\n//TODO: handle/process the output items if required\r\nConsole.WriteLine(outputItem.BaseObject.ToString());\r\n}\r\n}\r\n}\r\n///\u003csummary\u003e\r\n///Event handler for when data is added to the output stream.\r\n///\u003c/summary\u003e\r\n///\u003cparam name=\"sender\"\u003eContains the complete PSDataCollection of all output items.\u003c/param\u003e\r\n///\u003cparam name=\"e\"\u003eContains the index ID of the added collection item and the ID of the PowerShell instance\r\nvoidoutputCollection_DataAdded(objectsender,DataAddedEventArgse)\r\n{\r\n// do something when an object is written to the output stream\r\nConsole.WriteLine(\"Object added to output.\");\r\n}\r\n///\u003csummary\u003e\r\n///Event handler for when Data is added to the Error stream.\r\n///\u003c/summary\u003e\r\n///\u003cparam name=\"sender\"\u003eContains the complete PSDataCollection of all error output items.\u003c/param\u003e\r\n///\u003cparam name=\"e\"\u003eContains the index ID of the added collection item and the ID of the PowerShell instance\r\nvoidError_DataAdded(objectsender,DataAddedEventArgse)\r\n{\r\n// do something when an error is written to the error stream\r\nConsole.WriteLine(\"An error was written to the Error stream!\");\r\n}\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 7 of 16\n\nAs you can see above, the complete asynchronous model allows for some pretty interesting scenarios with long-running scripts. We can listen for events like data being added to the output stream. We can monitor the progress\r\nstream to see how much longer a task may take and provide feedback to the UI. We can listen for new errors being\r\nwritten to the error stream and react accordingly, instead of waiting until all execution has completed.\r\nExecution Policy:\r\nWhen you invoke cmdlets through the PowerShell class in C#, the execution policy behavior is subject to the\r\npolicy restrictions of the machine. This behavior is the same is if you opened up a PowerShell prompt on the\r\nmachine. You can issue commands just fine, but invoking another script might get blocked if your execution\r\npolicy is undefined or restricted in some way. An easy way to get around this is to set the execution policy for the\r\nscope of the application process. Simply run Set-ExecutionPolicy and specify the scope to be Process. This\r\nshould allow you to invoke secondary scripts without altering the machine/user policies. For more information\r\nabout policies and their order of precedence, see here.\r\nShared Namespace:\r\nTo wrap up our discussion, I’d like to share a potentially useful feature that can expand some of the functionality\r\nfor your scripts. When you use the PowerShell class to invoke a script, that script has access to the classes inside\r\nthe caller’s namespace, if they were declared public.\r\nIn the example code below, we make a public class with a single public property, and a public static class with a\r\nsingle public method. Both of these items exist in the same namespace as the PowerShell executor code. The\r\nscript we execute creates a new instance of the class, sets the property, and writes it to the pipeline. The static class\r\nand method are then called directly from inside the script, saving the results to a string which is then written to the\r\npipeline as well.\r\n namespacePowerShellExecutionSample\r\n{\r\n///\u003csummary\u003e\r\n///Test class object to instantiate from inside PowerShell script.\r\n///\u003c/summary\u003e\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 8 of 16\n\npublicclassTestObject\r\n{\r\n///\u003csummary\u003e\r\n///Gets or sets the Name property\r\n///\u003c/summary\u003e\r\npublicstringName{get;set;}\r\n}\r\n///\u003csummary\u003e\r\n///Test static class to invoke from inside PowerShell script.\r\n///\u003c/summary\u003e\r\npublicstaticclassTestStaticClass\r\n{\r\n///\u003csummary\u003e\r\n///Sample static method to call from insider PowerShell script.\r\n///\u003c/summary\u003e\r\n///\u003creturns\u003eString message\u003c/returns\u003e\r\npublicstaticstringTestStaticMethod()\r\n{\r\nreturn\"Hello, you have called the test static method.\";\r\n}\r\n}\r\n///\u003csummary\u003e\r\n///Provides PowerShell script execution examples\r\n///\u003c/summary\u003e\r\nclassPowerShellExecutor\r\n{\r\n///\u003csummary\u003e\r\n///Sample execution scenario 3: Namespace test\r\n///\u003c/summary\u003e\r\n///\u003cremarks\u003e\r\n///Executes a PowerShell script synchronously and utilizes classes in the callers namespace.\r\n///\u003c/remarks\u003e\r\npublicvoidExecuteSynchronouslyNamespaceTest()\r\n{\r\nusing(PowerShellPowerShellInstance=PowerShell.Create())\r\n{\r\n // add a script that creates a new instance of an object from the caller's namespace\r\nPowerShellInstance.AddScript(\"$t = new-object PowerShellExecutionSample.TestObject;\"+\r\n\"$t.Name = 'created from inside PowerShell script'; $t;\"+\r\n\"$message = [PowerShellExecutionSample.TestStaticClass]::TestStatic\r\n// invoke execution on the pipeline (collecting output)\r\nCollection\u003cPSObject\u003ePSOutput=PowerShellInstance.Invoke();\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 9 of 16\n\n// loop through each output object item\r\nforeach(PSObjectoutputIteminPSOutput)\r\n{\r\nif(outputItem!=null)\r\n{\r\nConsole.WriteLine(outputItem.BaseObject.GetType().FullName);\r\nif(outputItem.BaseObjectisTestObject)\r\n{\r\nTestObjecttestObj=outputItem.BaseObjectasTestObject;\r\nConsole.WriteLine(testObj.Name);\r\n}\r\nelse\r\n{\r\nConsole.WriteLine(outputItem.BaseObject.ToString());\r\n}\r\n}\r\n}\r\n}\r\n}\r\n}\r\n}\r\nAs we can see from the console output, the public static class and non-static class were both available from inside\r\nthe script for use. The ability to leverage public members from the caller’s namespace allows you to create some\r\ninteresting scenarios calling C# code directly from your PowerShell scripts.\r\nAnonymous\r\nJune 20, 2014\r\nHello.Nice article.I would like to ask you,what is the difference between runspace and powershell?When\r\ndo i use using (var runspace = RunspaceFactory.CreateRunspace()) and when powershell(the way you do\r\nit?).I have memory leak issues and still searching for a solution. Thanks!\r\nAnonymous\r\nJune 21, 2014\r\n@tasos: The runspace factory and the PowerShell class provide similar functionality. Runspace factory was\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 10 of 16\n\nintroduced early (powershell v1). The PowerShell instance class stuff was introduced in v2 I believe. The\r\nv2 method is just a little bit easier to use.\r\nAnonymous\r\nJune 22, 2014\r\nThe comment has been removed\r\nAnonymous\r\nJune 24, 2014\r\nI don't know why you would be having memory leaks. If you are still having problems I would recommend\r\nasking for support on the MSDN forums, they should be able to help you over there.\r\nsocial.msdn.microsoft.com/.../home\r\nAnonymous\r\nJuly 08, 2014\r\nExcellent and well written article. Love the examples. Thank you!\r\nAnonymous\r\nAugust 07, 2014\r\nAnd of course you have a downloadable test project to go along with the article...\r\nAnonymous\r\nAugust 07, 2014\r\n@MSTech - just updated the top of the article and posted a link to the solution.\r\nAnonymous\r\nAugust 26, 2014\r\nOutstanding article ... especially appreciated the namespace example.\r\nAnonymous\r\nSeptember 10, 2014\r\nHi Keith, Thanks for the wonderful article. I tried to import and run the code you have supplied above. I\r\nam getting the following error message \"Could not load file or assembly 'System.Management.Automation,\r\nVersion=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Strong\r\nname validation failed. (Exception from HRESULT: 0x8013141A)\" could you please help me resolving\r\nthis. I am able to see the System.Management.Automation.dll in the same location as you mentioned in\r\nyour code. Thanks in Advance.\r\nAnonymous\r\nSeptember 10, 2014\r\n@Dan, I haven't run into that before. Are you running it from the downloadable solution link above? Or did\r\nyou copy and paste the code snippets into a brand new project of your own? If its a brand new project,\r\nwhat .net framework version did you target?\r\nAnonymous\r\nSeptember 10, 2014\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 11 of 16\n\n@Keith I am running the downloadable solution link provided above.  I am getting the above error when I\r\nam running t.ExecuteSynchronously(); statement.\r\nAnonymous\r\nSeptember 11, 2014\r\n@Dan - one thing I would try would be to remove the reference to the assembly, and then re-add it back to\r\nthe project. Alternatively, create a new project in Visual Studio, add the assembly reference, and try some\r\nof the sample code in that new project. See if that helps.  If you are still having issues after that I would\r\nrecommend heading over to the MSDN forums for support.\r\nAnonymous\r\nOctober 08, 2014\r\nIs there any way to specify the user that runs the power shell instance? I'd like to user a different use to that\r\nwhich runs the application.\r\nAnonymous\r\nOctober 16, 2014\r\nHello, thanks for the article. We’re trying to automate some of our PowerShell CmdLets in C#. In\r\nPowerShell Cmd we are getting an PSObject which has one more object nested. E.g: $a = Get-XYZ $a has\r\nsome properties say prop1, prop2  etc. $a.prop1 also has some properties say prop1-1, prop1-2 Please help\r\nme in getting values of prop1-1, prop1-2 via C#. we were able to access prop1 and prop2 as\r\nPSMemberInfo.\r\nAnonymous\r\nOctober 28, 2014\r\nThe comment has been removed\r\nAnonymous\r\nOctober 29, 2014\r\n@Greg - by default the PowerShell instance will be run under the user context of the hosting process. I am\r\nnot aware of any additional parameters or configuration to provide to the PowerShell class that would\r\nallow it to run as a different user. The solution to this problem really depends on the design and purpose of\r\nyour application. Without more info its hard to say.\r\nAnonymous\r\nOctober 29, 2014\r\n@Shanmuk - If you know the object type, can you try casting the PSObject (or PSObject.BaseObject) into\r\nyour known class and access the properties that way?\r\nAnonymous\r\nOctober 29, 2014\r\n@Carlos - Unfortunately I don't have any experience with MVC applications, but I have solved a similar\r\nproblem in WCF web services using caching. What you could do is store a collection of fully initialized\r\nPowerShell instances in the web cache. Then when a user makes a request that requires PS, it just grabs\r\none from the cache instead of initializing a brand new one.\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 12 of 16\n\nAnonymous\r\nNovember 19, 2014\r\nI have installed Powershell 5.0 and i am calling powershell scripts from C# then the first script is executing\r\nfine but second script is blocked by first. I got error. Even I tried to set executionpolicy Unrestricted -scope\r\nprocess. Still no luck. My current execution policy is as follows:                                                         Scope  \r\n                                       ExecutionPolicy                                                         -----                                          \r\n    ---------------                                                 MachinePolicy                                     Undefined                    \r\n                               UserPolicy                                         Undefined                                                      \r\nProcess                                           Unrestricted                                                   CurrentUser                          \r\n            RemoteSigned                                                  LocalMachine                                     Unrestricted\r\nPlease suggest me how to resolve this error.\r\nAnonymous\r\nNovember 20, 2014\r\n@Pushpa, was the 2nd script downloaded from the internet, and potentially blocked (at the file)? Please\r\nprovide the error message.\r\nAnonymous\r\nNovember 22, 2014\r\nI use the the following code and it sends the output to text box only on completion of entire script. Can we\r\nuse the same code when executing the power shell script via the aspx page ?,\r\nPSshell.Commands.AddScript(PSInput);           IAsyncResult async = PSshell.BeginInvoke();          \r\nResponse.Write(async.ToString());           ResultBox_ps.Text += async.ToString() + \"rn\";          \r\nPSshell.EndInvoke(async);                foreach (PSObject result in PSshell.EndInvoke(async))                {      \r\n            ResultBox_ps.Text += result.ToString() + \"rn\";                }\r\nAnonymous\r\nDecember 18, 2014\r\nI had the problem with memory leak either. Then I used RunspaceFactory.CreateOutOfProcessRunspace\r\nand memory leak gone.\r\nAnonymous\r\nFebruary 22, 2015\r\nthanks for the information but I want to build a cmdlet using the c# which does the work of making a\r\nconnection. if you know can you please help. thanks in advance\r\nAnonymous\r\nMarch 02, 2015\r\nThe comment has been removed\r\nAnonymous\r\nMarch 12, 2015\r\n@dan and for anyone else facing this issue. \"Thanks for the wonderful article. I tried to import and run the\r\ncode you have supplied above. I am getting the following error message \"Could not load file or assembly\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 13 of 16\n\n'System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'\r\nor one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)\"\r\ncould you please help me resolving this. I am able to see the System.Management.Automation.dll in the\r\nsame location as you mentioned in your code.\" After hours of research, this is what I had to do.\r\n1. update my .csproj file to say    \u003cReference Include=\"System.Management.Automation, Version=3.0.0.0,\r\nCulture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\"\u003e    \r\n \u003cSpecificVersion\u003eFalse\u003c/SpecificVersion\u003e      \u003cHintPath\u003eC:Program Files (x86)Reference\r\nAssembliesMicrosoftWindowsPowerShell3.0System.Management.Automation.dll\u003c/HintPath\u003e  \r\n \u003c/Reference\u003e\r\n2. Target a lower version of .Net. I targeted 4.0 just like in the sample solution. Before I was targeting 4.5,\r\nwhich was wrong. After this, it started working. Good luck and hope you guys find this helpful.\r\nwww.qtptutorial.net\r\nAnonymous\r\nApril 08, 2015\r\nfor strong name issue here is the solution stackoverflow.com/.../error-loading-system-management-automation-assembly\r\nAnonymous\r\nApril 17, 2015\r\nThanks for this article! Really appreciated it. If anyone else had trouble figuring out how to get error output\r\nwithin the Error_DataAdded method see below void Error_DataAdded(object sender,\r\nDataAddedEventArgs e) {            var records = (PSDataCollection\u003cErrorRecord\u003e)sender;            // do\r\nsomething when an error is written to the error stream          \r\n Console.WriteLine(records[e.Index].ToString()); }\r\nAnonymous\r\nMay 02, 2015\r\nThanks so much for the article :) Can I ask you something, why Am I getting this result?\r\nhttp://1drv.ms/1dDZJOq Thanks in advance, Cheers\r\nAnonymous\r\nMay 07, 2015\r\nGreat Article The only one on the net concernig startig PS async from c#. Could you maybe add an\r\nexample with Output in a mulitiline TextBox of ListBox in windows form application. I am struggling with\r\nit. The First powershell script command result is shown in LIstBox and after that application is freezing...\r\nThanks in advance and regards\r\nAnonymous\r\nMay 14, 2015\r\nHow are you guys finding these memory leaks?   I've used the above methods and love it - everything\r\nappears to be going great, but I'd like to make sure?\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 14 of 16\n\nAnonymous\r\nMay 19, 2015\r\nHi Keith The link to download appears broken. Could you please update? Many thanks!\r\nAnonymous\r\nMay 20, 2015\r\n@AMO Just tested the link its working for me.\r\nAnonymous\r\nJuly 23, 2015\r\nHello Keith, Can you please hep me with how to get the list of Properties associated an PSObject while\r\niterating the PSObject collection returned by below function:        string exCmdletResult = \"\";        private\r\nCollection\u003cPSObject\u003e CmdletResults(string PSScriptText)        {            exCmdletResult = \"\";          \r\n Collection\u003cPSObject\u003e PSOutput = null;            PowerShell ps = PowerShell.Create();          \r\n ps.AddScript(PSScriptText);            try            {                PSOutput = ps.Invoke();            }            catch\r\n(Exception ex) { exCmdletResult = \"Error: \" + ex.Message; }            finally { ps.Dispose(); }            return\r\nPSOutput;        } I am calling the same through this button click even on a windows form:        private void\r\nbtnExecute_Click(object sender, EventArgs e)        {            string cmd_Script = txtCommand.Text;          \r\n string commandOutput = \"\";            Collection\u003cPSObject\u003e results = CmdletResults(cmd_Script);            if\r\n(exCmdletResult.Contains(\"Error: \"))            {                txtOutput.Text = exCmdletResult;            }          \r\n else            {                foreach (PSObject result in results)                {                    // How to get the list of\r\nproperties when you don't know the command                }            }            txtOutput.Text =\r\ncommandOutput;        } Thanks and regards, Savindra\r\nAnonymous\r\nJuly 26, 2015\r\nThe comment has been removed\r\nAnonymous\r\nJuly 27, 2015\r\ncan i pass the output from the powershell script into a datatable or a list object? i want 2 columns fullname\r\nand name in a way i can check it against a database to see if that file already exists\r\nAnonymous\r\nAugust 18, 2015\r\nI just started doing this. An unhandled exception of type\r\n'System.Management.Automation.PSInvalidOperationException' occurred in\r\nSystem.Management.Automation.dll I think its because Powershell wont allow its access from outside.\r\nWhat should I do ?\r\nAnonymous\r\nAugust 31, 2015\r\nThe comment has been removed\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 15 of 16\n\nAnonymous\r\nOctober 21, 2015\r\nhehe private string spaceCharacter = \"` \"; and the parameters are for powershell.exe , not the script\r\nAnonymous\r\nNovember 05, 2015\r\nI have everything from your article working but.I can't get the \"get-service\" to return anything but\r\n\"System.ServiceProcess.ServiceController\".   I tried putting the result in a $sc  variable and then displaying\r\nit.  Still nothing.  What am I missing?     I notice it  has the same problem if I substitute \"Get-ChildItem\"\r\nfor \"Get-Service\".      Thanks so much for a very helpful article.  \r\nAnonymous\r\nFebruary 22, 2016\r\nThank You! Great article!\r\nSource: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nhttps://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/\r\nPage 16 of 16",
	"extraction_quality": 1,
	"language": "EN",
	"sources": [
		"MITRE"
	],
	"references": [
		"https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/"
	],
	"report_names": [
		"executing-powershell-scripts-from-c"
	],
	"threat_actors": [],
	"ts_created_at": 1775434818,
	"ts_updated_at": 1775791298,
	"ts_creation_date": 0,
	"ts_modification_date": 0,
	"files": {
		"pdf": "https://archive.orkl.eu/dfd5644684109d0c133c84e6ea203bdad2ccafea.pdf",
		"text": "https://archive.orkl.eu/dfd5644684109d0c133c84e6ea203bdad2ccafea.txt",
		"img": "https://archive.orkl.eu/dfd5644684109d0c133c84e6ea203bdad2ccafea.jpg"
	}
}