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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like it was added in Powershell 3
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.