{"id":91684,"date":"2023-06-22T08:00:57","date_gmt":"2023-06-22T06:00:57","guid":{"rendered":"https:\/\/code-maze.com\/?p=91684"},"modified":"2023-06-22T08:42:41","modified_gmt":"2023-06-22T06:42:41","slug":"csharp-run-powershell-script","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-run-powershell-script\/","title":{"rendered":"Execute a PowerShell Script in C#"},"content":{"rendered":"<p>In this article, we\u2019ll learn how to execute a PowerShell script in C# using the ProcessStartInfo class from <code>System.Diagnostics<\/code> namespace and PowerShell classes from the <code>System.Management.Automation<\/code> namespace, which is available in <code>PowerShell.SDK<\/code>.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/dotnet-cli\/ExecutingPowerShellScript\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s see how to do that!<\/p>\n<h2>Use the ProcessStartInfo Class to Execute a PowerShell Script in C#<\/h2>\n<p>.NET provides users with a\u00a0<code>ProcessStartInfo<\/code> class that enables us to configure, start and stop a process. We can leverage this class to invoke PowerShell commands and scripts. To learn more about <code>ProcessStartInfo<\/code> class, please check the article on <a href=\"https:\/\/code-maze.com\/csharp-execute-cli-applications\/\" target=\"_blank\" rel=\"noopener\">How to execute CLI Applications From C#<\/a>.<\/p>\n<p>Let&#8217;s start by creating a simple <code>.ps1<\/code> file with this content:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">I am invoked using ProcessStartInfoClass!<\/code><\/p>\n<p>Next, we will create a function to execute our script:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string ExecuteScript(string pathToScript)\r\n{\r\n    var scriptArguments = \"-ExecutionPolicy Bypass -File \\\"\" + pathToScript + \"\\\"\";\r\n    var processStartInfo = new ProcessStartInfo(\"powershell.exe\", scriptArguments);\r\n    processStartInfo.RedirectStandardOutput = true;\r\n    processStartInfo.RedirectStandardError = true;\r\n    \r\n    using var process = new Process();\r\n    process.StartInfo = processStartInfo;\r\n    process.Start();\r\n    string output = process.StandardOutput.ReadToEnd();\r\n    string error = process.StandardError.ReadToEnd();\r\n    Console.Writeline(output); \/\/ I am invoked using ProcessStartInfoClass!\r\n}<\/pre>\n<p>When we create a new <code>ProcessStartInfo<\/code> instance we have to provide two arguments &#8211; the file name and command line arguments. Thus, we set the <code>ExecutionPolicy Bypass<\/code>, which ensures that we can run our scripts with no restrictions.<\/p>\n<p>Then, we invoke the process using <code>ProcessStartInfo<\/code> class. We do that by creating a new <code>Process<\/code> instances and assigning the created <code>processStartInfo<\/code> object to the <code>StartInfo<\/code> property.<\/p>\n<p>When we start a process using <code>Process.Start<\/code>, the process has its own standard output and standard error streams where it will write output and error messages. By default, the calling process is not catching these streams. That is why we set <code>RedirectStandardOutput<\/code>\u00a0and <code>RedirectStandardError<\/code> properties to\u00a0 <code>true<\/code>. We instruct the <code>Process<\/code> object to redirect the standard output and standard error streams so that we can capture and read them programmatically.<\/p>\n<p>Lastly, we take the results from the output and error streams respectively and safely dispose of the process by including <code>using<\/code> statement.<\/p>\n<p>Now, let&#8217;s modify our code and see how simple we can execute PowerShell commands directly instead of running a script. All we need to do is change the setup of the <code>ProcessStartInfo<\/code> class slightly:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public string ExecuteCommand(string command)\r\n{\r\n    var processStartInfo = new ProcessStartInfo();\r\n    processStartInfo.FileName = \"powershell.exe\";\r\n    processStartInfo.Arguments = $\"-Command \\\"{command}\\\"\";\r\n    processStartInfo.UseShellExecute = false;\r\n    processStartInfo.RedirectStandardOutput = true;\r\n    \r\n    using var process = new Process();\r\n    process.StartInfo = processStartInfo;\r\n    process.Start();\r\n    string output = process.StandardOutput.ReadToEnd();\r\n    Console.Writeline(output);\r\n}<\/pre>\n<p>We configure it in a similar manner except now the <code>Arguments<\/code> include a\u00a0<code>command<\/code> variable that we will specify when invoking the function:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">ExecuteCommand(\"I am invoked using echo command!\"); \/\/ I am invoked using echo command!<\/code><\/p>\n<p>To sum up, when we use the <code>ProcessStartInfo<\/code> class to execute a PowerShell script, we actually start a\u00a0<code>PowerShell.exe<\/code> on our local system by calling <code>process.Start<\/code> and passing it all the necessary arguments to execute our commands.<\/p>\n<h2>Use the PowerShell Class to Execute a PowerShell Script in C#<\/h2>\n<p>We can also use the <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/System.Management.Automation.PowerShell?view=powershellsdk-7.2.0\" target=\"_blank\" rel=\"nofollow noopener\">PowerShell<\/a> class from the <code>PowerShell.SDK<\/code> to execute our commands and scripts in C#. Let&#8217;s start by referencing the\u00a0 <code>Microsoft.PowerShell.SDK<\/code>, which gives us access to the <code>System.Management.Automation<\/code> namespace:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using System.Management.Automation;<\/code><\/p>\n<p><code>PowerShell.SDK<\/code> offers us a lot of flexibility for executing commands and scripts and enables us to create custom runspaces, which we will cover later.<\/p>\n<p>The main difference between using the <code>PowerShell<\/code> class and the <code>ProcessStartInfo<\/code> class is that the <code>PowerShell<\/code> class creates our PowerShell instance in our application, so we do not need to invoke an external PowerShell process to execute commands.<\/p>\n<p>Let&#8217;s see how simple it is to execute a script.<\/p>\n<p>This time we&#8217;ll create a simple <code>echo.ps1<\/code> script:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">'I am invoked by PowerShell class!'<\/code><\/p>\n<p>Now let&#8217;s invoke this script using the <code>PowerShell<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">PowerShell ps = PowerShell.Create();\r\nps.AddScript(@\".\\echo.ps1\").Invoke();<\/pre>\n<p>We simply pass the path to our script to invoke our <code>echo.ps1<\/code> script.<\/p>\n<p>Let&#8217;s execute a simple command directly this time, we&#8217;ll use <code>Get-Date<\/code> to get the current date time:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using var ps = PowerShell.Create();\r\nps.AddCommand(\"Get-Date\"); \r\nvar processes = ps.Invoke(); \r\nConsole.WriteLine(processes.First().ToString()); \/\/ 10\/05\/2023 19:12:34<\/pre>\n<p>Notice that we instantiate the <code>PowerShell<\/code> class in the using statement to dispose of it properly after. We create a <code>PowerShell<\/code> instance, add a command and invoke it.<\/p>\n<p>To display the resulting objects to the console, we just use the <code>First<\/code> method and convert the result to a string.<\/p>\n<p>As we can see, as long as we know the command in PowerShell, we can easily transform it and use it in C#. Let us try one more example where we start a process which is the notepad:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using var ps = PowerShell.Create();\r\nps.AddCommand(\"Start-Process\").AddArgument(\"notepad\");\r\nps.Invoke(); \r\n<\/pre>\n<p>Notice that the <code>PowerShell<\/code> class allows method chaining. We use the <code>AddArgument()<\/code> method after the <code>AddCommand()<\/code> method.<\/p>\n<p>By default, the <code>PowerShell<\/code> class uses the <a href=\"https:\/\/learn.microsoft.com\/en-us\/powershell\/scripting\/developer\/hosting\/windows-powershell-host-quickstart?view=powershell-7.3#using-the-default-runspace\" target=\"_blank\" rel=\"nofollow noopener\">default runspace<\/a> to run the script and execute commands. The default runspace represents the default execution environment for our commands and scripts.<\/p>\n<p>Let&#8217;s see how to use a custom runspace.<\/p>\n<h3>Custom Runspace<\/h3>\n<p>Alongside security reasons, we might use a custom runspace for performance gains. This is because we limit the runspace to a specified subset of commands that we actually need. That means that a runspace loads only the commands that we specify.<\/p>\n<p>First, we need to create an <code>InitialSessionState<\/code> object. This class allows us to define a set of elements that should be present when a\u00a0<code>SessionState<\/code> is created. The <code>SessionStateVariableEntry<\/code> class allows us to create new session state variables.<\/p>\n<p>A session state variable is a variable that persists for the entire session, similar to a global variable. We need it because it represents the set of allowed commands we can use in our runspace throughout the session. <code>SessionState<\/code> refers to the current configuration of a Windows\u00a0<code>PowerShell<\/code> session or module.<\/p>\n<p>Basically, the <code>PowerShell<\/code> session refers to the time from starting a host application that opens\u00a0 PowerShell runspace up until it closes the runspace. We will apply all our restrictions to this <code>InitialSessionState<\/code> object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">InitialSessionState iss = InitialSessionState.Create();\r\nvar entry = new SessionStateVariableEntry(\"AllowedCommands\", \r\n    new[] { \"Get-Date\" }, \"List of allowed commands\");\r\niss.Variables.Add(entry);<\/pre>\n<p>Here we allow only a single command to be used, the <code>Get-Date<\/code> command.\u00a0<\/p>\n<p>Next, we need to import the <code>Microsoft.PowerShell.Utility<\/code> module that contains this command and apply the command to the <code>InitialSessionState<\/code> object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var ms = new ModuleSpecification(\"Microsoft.PowerShell.Utility\");\r\niss.ImportPSModule(new[] { ms });\r\n\r\nvar getDateCmdlet = new SessionStateCmdletEntry(\"Get-Date\", \r\n    typeof(Microsoft.PowerShell.Commands.GetDateCommand), \"\");\r\niss.Commands.Add(getDateCmdlet);<\/pre>\n<p>Now we can create and run our runspace to use the configured <code>InitialSessionState<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Runspace rs = RunspaceFactory.CreateRunspace(iss);\r\nrs.Open();<\/pre>\n<p>All that remains now is to apply our custom runspace to the <code>PowerShell<\/code> instance and to try it out:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">using var ps = PowerShell.Create();\r\nps.Runspace = rs;\r\nps.AddCommand(\"Get-Date\");\r\nvar processes= ps.Invoke();\r\nConsole.WriteLine(processes.First().ToString()); \/\/ 10\/05\/2023 20:15:34    <\/pre>\n<p>As expected, we got the time and date printed on the console.<\/p>\n<p>Lastly, let&#8217;s try to run the <code>Start-Process<\/code> command instead, which is not in our custom runspace. To better understand what is happening, we will create a method that returns <code>true<\/code> or <code>false<\/code> depending on the execution result of our command:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public bool StartProcess(string processName)\r\n{\r\n    try\r\n    {\r\n        using (var ps = PowerShell.Create())\r\n        {\r\n            ps.Runspace = rs;\r\n            ps.AddCommand(\"Start-Process\").AddArgument(processName);\r\n            ps.Invoke();\r\n            return true;\r\n        }\r\n    }\r\n    catch (Exception)\r\n    {\r\n        return false;\r\n    }\r\n}<\/pre>\n<p>Next, let&#8217;s print the result to the console:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var processStarted = StartProcess(\"notepad\");\r\nif (!processStarted)\r\n{\r\n    Console.WriteLine(\"This is a custom runspace that can only run Get-Date command\");\r\n}<\/pre>\n<p>Our custom runspace does not recognize the command and throws an exception with the message. This shows we have successfully created a restricted runspace.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we reviewed two ways to execute a PowerShell script in C#. We first covered using the <code>ProcessStartInfo<\/code> class. Next, we focused on the <code>PowerShell<\/code> class from the <code>PowerShell.SDK<\/code>\u00a0and the difference between this class and the <code>ProcessStartInfo<\/code> class. Lastly, we took a step further by looking at a custom runspace where we can restrict which commands can be executed.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we\u2019ll learn how to execute a PowerShell script in C# using the ProcessStartInfo class from System.Diagnostics namespace and PowerShell classes from the System.Management.Automation namespace, which is available in PowerShell.SDK. Let&#8217;s see how to do that! Use the ProcessStartInfo Class to Execute a PowerShell Script in C# .NET provides users with a\u00a0ProcessStartInfo class [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[1001,12],"tags":[10,1811,998,1843,1844],"class_list":["post-91684","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-net-cli","category-csharp","tag-net","tag-c","tag-cli","tag-powershell","tag-runspace","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Execute a PowerShell Script in C#<\/title>\n<meta name=\"description\" content=\"In this article, we\u2019ll show how to execute a PowerShell script in C# using the ProcessStartInfo and PowerShell classes.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-run-powershell-script\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Execute a PowerShell Script in C#\" \/>\n<meta property=\"og:description\" content=\"In this article, we\u2019ll show how to execute a PowerShell script in C# using the ProcessStartInfo and PowerShell classes.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-run-powershell-script\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-22T06:00:57+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-06-22T06:42:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Execute a PowerShell Script in C#\",\"datePublished\":\"2023-06-22T06:00:57+00:00\",\"dateModified\":\"2023-06-22T06:42:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/\"},\"wordCount\":1018,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\".NET\",\"C#\",\"CLI\",\"powershell\",\"runspace\"],\"articleSection\":[\".NET CLI\",\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/\",\"url\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/\",\"name\":\"Execute a PowerShell Script in C#\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2023-06-22T06:00:57+00:00\",\"dateModified\":\"2023-06-22T06:42:41+00:00\",\"description\":\"In this article, we\u2019ll show how to execute a PowerShell script in C# using the ProcessStartInfo and PowerShell classes.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-run-powershell-script\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-run-powershell-script\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Execute a PowerShell Script in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Execute a PowerShell Script in C#","description":"In this article, we\u2019ll show how to execute a PowerShell script in C# using the ProcessStartInfo and PowerShell classes.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-run-powershell-script\/","og_locale":"en_US","og_type":"article","og_title":"Execute a PowerShell Script in C#","og_description":"In this article, we\u2019ll show how to execute a PowerShell script in C# using the ProcessStartInfo and PowerShell classes.","og_url":"https:\/\/code-maze.com\/csharp-run-powershell-script\/","og_site_name":"Code Maze","article_published_time":"2023-06-22T06:00:57+00:00","article_modified_time":"2023-06-22T06:42:41+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Execute a PowerShell Script in C#","datePublished":"2023-06-22T06:00:57+00:00","dateModified":"2023-06-22T06:42:41+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/"},"wordCount":1018,"commentCount":1,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":[".NET","C#","CLI","powershell","runspace"],"articleSection":[".NET CLI","C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-run-powershell-script\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/","url":"https:\/\/code-maze.com\/csharp-run-powershell-script\/","name":"Execute a PowerShell Script in C#","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2023-06-22T06:00:57+00:00","dateModified":"2023-06-22T06:42:41+00:00","description":"In this article, we\u2019ll show how to execute a PowerShell script in C# using the ProcessStartInfo and PowerShell classes.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-run-powershell-script\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-run-powershell-script\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Execute a PowerShell Script in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/91684","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=91684"}],"version-history":[{"count":6,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/91684\/revisions"}],"predecessor-version":[{"id":91727,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/91684\/revisions\/91727"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=91684"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=91684"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=91684"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}