[英]Script that runs fine on PowerShell returns error using System.Management.Automation.PowerShell
I'm writing a C# program that uses PowerShell to renew certificates by LetsEncrypt, but I can't get passed the first line. 我正在编写一个使用PowerShell通过LetsEncrypt更新证书的C#程序,但是我无法通过第一行。
My code: 我的代码:
using (var ps = PowerShell.Create()) {
ps.AddScript("Import-Module ACMESharp");
ps.Invoke();
output = ps.HadErrors
? ps.Streams.Error.ToString()
: ps.Streams.Information.ToString();
return !ps.HadErrors;
}
The result is that I'm getting an error: 结果是我得到一个错误:
The specified module 'ACMESharp' was not loaded because no valid module file was found in any module directory.
未加载指定的模块“ ACMESharp”,因为在任何模块目录中均未找到有效的模块文件。
but when I run the same command in PowerShell, it works fine. 但是当我在PowerShell中运行相同的命令时,它可以正常工作。
How can I fix this? 我怎样才能解决这个问题?
Your codes fails when running it without Administrator privileges and works when running it as Admin. 如果在没有管理员特权的情况下运行代码,则代码将失败,而在以Admin身份运行时,代码将起作用。
Set your C# app to run with Admin privileges: 将您的C#应用设置为以管理员权限运行:
Administrator
". Administrator
”身份运行Visual Studio。 If you are planing to deploy the application, your need add this to your application manifest . 如果您打算部署应用程序,则需要将其添加到应用程序清单中 。
<requestedExecutionLevel level="requireAdministrator" uiAccess="true"/>
Edit: 编辑:
Another reason for Import-Module
to fail is that specified module ACMESharp
does not exist in the PSModulePath
variable. Import-Module
失败的另一个原因是PSModulePath
变量中不存在指定的模块ACMESharp
。 In this case, there is no way for PowerShell
to find the module to import. 在这种情况下,
PowerShell
无法找到要导入的模块。
You could explicitly add another path by appending the path to the existing PSModulePath list of paths. 您可以通过将路径追加到现有的PSModulePath路径列表中来显式添加其他路径。
var extraModulesPath = "somepath";
var state = InitialSessionState.CreateDefault();
using (var rs = RunspaceFactory.CreateRunspace(state))
{
rs.Open();
using (var ps = PowerShell.Create())
{
ps.Runspace = rs;
var psModulePath = rs.SessionStateProxy.GetVariable("env:PSModulePath");
rs.SessionStateProxy.SetVariable("env:PSModulePath", $"{psModulePath};{extraModulesPath}");
ps.AddScript("Import-Module('ACMESharp')");
ps.Invoke();
var output = ps.HadErrors
? ps.Streams.Error.ToString()
: ps.Streams.Information.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.