【发布时间】:2017-01-18 04:02:17
【问题描述】:
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
- 分配的访问权限
- BitLocker
- 配置CI
- 后卫
- Microsoft.PowerShell.LocalAccounts
- MMAgent
- 网络交换机管理器
- PcsvDevice
- PSWorkflow、PSWorkflowUtility
- SmbShare、SmbWitness
- 开始布局
- Windows 搜索
版本 ($PSVersionTable) 在两个 shell 中报告为相同:5.1.14393.693
编辑
似乎是同一个问题和解决方案:Why do powershell modules not import when running powershell via start process in c#?
【问题讨论】:
-
您可以将
Import-Module与该模块的完整路径一起使用,或者必须设置/修复PSModulePath,这是我的猜测。无论出于何种原因,在这种情况下都会有所不同。
标签: c# powershell