7

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?

user685590
  • 2,464
  • 5
  • 30
  • 42

2 Answers2

9

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.

  • 1
    Looks like it was added in [Powershell 3](http://technet.microsoft.com/en-us/library/hh849898(v=wps.620).aspx) – Travis Mar 07 '14 at 17:41
1
system("powershell -command '<some commands> | ConvertFrom-Json | <other commands>' ");

will also throw the same error

In that case, you need to change the single quotes to double quotes and use the escape character so that the double quotes get passed along.

I think this is because of this?