从C#运行的PowerShell脚本缺少几个模块

时间:2017-01-17 01:25:49

标签: c# powershell

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

C#启动的运行时中缺少常规shell中存在的某些cmdlet,例如:来自Microsoft.PowerShell.LocalAccounts模块的所有命令:

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)

通过比较常规shell和C#启动的Get-Module -ListAvailable输出,我注意到缺少多个模块:

  • AppBackgroundTask
  • AssignedAccess
  • BitLocker的
  • ConfigCI
  • 后卫
  • Microsoft.PowerShell.LocalAccounts
  • MMAgent
  • NetworkSwitchManager
  • PcsvDevice
  • PSWorkflow,PSWorkflowUtility
  • SmbShare,SmbWitness
  • StartLayout
  • Windows搜索

两个shell中的版本($PSVersionTable)报告相同:5.1.14393.693

修改

似乎是同一个问题&解决方案:Why do powershell modules not import when running powershell via start process in c#?

1 个答案:

答案 0 :(得分:0)

您可以直接在脚本上导入模块,而不是尝试从C#执行此操作。

  

导入模块bitlocker

例如。