简体   繁体   中英

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.

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.

but when I run the same command in PowerShell, it works fine.

How can I fix this?

Your codes fails when running it without Administrator privileges and works when running it as Admin.

Set your C# app to run with Admin privileges:

  1. If you are running in Visual Studio and debugging only, run the Visual Studio as " Administrator ".
  2. 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. In this case, there is no way for PowerShell to find the module to import.

You could explicitly add another path by appending the path to the existing PSModulePath list of paths.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM