1
var runspace = RunspaceFactory.CreateRunspace()
runspace.Open();
var ps = PowerShell.Create()
ps.Runspace = runspace;
ps.AddCommand(...);
ps.Invoke()

Some cmdlets that exist in a regular shell are missing from the runtime started by C#, e.g. all the commands from the Microsoft.PowerShell.LocalAccounts module :

Error: System.Management.Automation.CommandNotFoundException: The term 'New-LocalUser' 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.
  at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
  at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
  at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
  at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

By comparing the Get-Module -ListAvailable output from a regular shell and a C# started one I noticed multiple modules are missing :

  • AppBackgroundTask
  • AssignedAccess
  • BitLocker
  • ConfigCI
  • Defender
  • Microsoft.PowerShell.LocalAccounts
  • MMAgent
  • NetworkSwitchManager
  • PcsvDevice
  • PSWorkflow, PSWorkflowUtility
  • SmbShare, SmbWitness
  • StartLayout
  • WindowsSearch

The version ($PSVersionTable) is reported as the same in both shells : 5.1.14393.693

Edit

Seems to be the same issue & solution : Why do powershell modules not import when running powershell via start process in c#?

1
  • You could use Import-Module with the complete path for that module or would have to set/fix the PSModulePath, that would be my guess. For whatever reason it's different in that case. Commented Jan 17, 2017 at 13:50

1 Answer 1

0

You can import modules directly on your script instead of trying to do that from C#.

Import-module bitlocker

For example.

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

2 Comments

Does not help. Actually, according to MSDN : Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command.
Did you check the version of PowerShell that is being started?

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.