I would like to run power shell scripts in c#.
Using the tutorial on running powershell scripts in c# from CodeProject (http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C)
I am able to run 'most' ps scripts (they run perfect in PS), but the one I require, I receive an error when trying to use the -ConvertFrom-Json command.
Error in script : The term 'ConvertFrom-Json' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I am new to this so not sure if its out of date libraries or other dependencies that are needed to make it work?
In File Explorer (or Windows Explorer), right-click the script file name and then select "Run with PowerShell". The "Run with PowerShell" feature starts a PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.
ps1 files are interpreted by PowerShell, the Command Prompt (CMD) cannot work with PowerShell scripts directly. If you would like to run a PowerShell script in CMD, you'll need to execute it by calling the PowerShell process with the -File parameter, as shown below: PowerShell -File C:\TEMP\MyNotepadScript. ps1.
Since ConvertFrom-Json was introduced in Powershell 3.0, ensure that the runspace that you are creating is also Powershell 3.0+. You can do this by executing $Host.Version
in the context of your C# code and looking at the Version object returned. It should have a Major Version of 3 or 4.
If it is 3.0+, since ConvertFrom-Json is included via the module Microsoft.PowerShell.Utility
, make sure that the module is loaded by doing Import-Module Microsoft.PowerShell.Utility
before your ConvertFrom-Json. The module is probably getting loaded via your normal session initialization scripts, but when being executed from code, it may not be executing those.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With