gpt4 book ai didi

c# - 在 C# 运行空间中的远程服务器上导入 Powershell 模块

转载 作者:行者123 更新时间:2023-12-03 01:22:21 24 4
gpt4 key购买 nike

我需要能够通过 C# 运行空间导入驻留在远程机器上的模块。

为了明确我的意思:我正在创建的服务位于服务器 A 上。它使用以下方法创建到服务器 B 的远程运行空间。通过运行空间,我试图在服务器 B 上导入一个模块。

这是我用来进行远程调用的方法:

internal Collection<PSObject> RunRemoteScript(string remoteScript, string remoteServer, string scriptName, out bool scriptSuccessful)
{
bool isLocal = (remoteServer == "localhost" || remoteServer == "127.0.0.1" || remoteServer == Environment.MachineName);

WSManConnectionInfo connectionInfo = null;

if (!isLocal)
{
connectionInfo = new WSManConnectionInfo(new Uri("http://" + remoteServer + ":5985"));
}

PsHostImplementation myHost = new PsHostImplementation(scriptName);

using (Runspace remoteRunspace = (isLocal ? RunspaceFactory.CreateRunspace(myHost) : RunspaceFactory.CreateRunspace(myHost, connectionInfo)))
{
remoteRunspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = remoteRunspace;

Pipeline pipeline = remoteRunspace.CreatePipeline();

pipeline.Commands.AddScript(remoteScript);

Collection<PSObject> results = pipeline.Invoke();

remoteRunspace.Close();

scriptSuccessful = myHost.ScriptSuccessful;
return results;
}
}
}

“remoteScript”设置为我要运行的 Powershell 脚本。例如:
"Import-Module Modulename;CustomCommand-FromModule -parameter(s) -ErrorAction stop"

该模块没有打包在一起,它是一个 psd1、psm1 和一堆脚本文件,它们位于远程服务器(服务器 B)上的 C:\\Powershell\ModuleName 中,我已经测试并确保它正在调用 ModuleName。 C:\\Powershell\ModuleName 目录中的 psd1 文件。

ModuleName.psd1 文件中包含以下行:
ModuleToProcess = 'ModuleName.psm1'

但是,如果我尝试通过 c# 运行空间运行它,我会收到一个非常奇怪的错误。

如果我将以下内容作为参数发送到“remoteScript”:
"Import-Module Modulename"

我收到以下错误:

System.Management.Automation.RemoteException: The module to process 'ModuleName.psm1', listed in field 'ModuleToProcess' of module manifest 'C:\Powershell\ModuleName\ModuleName.psd1' was not processed because no valid module was found in any module directory.



该模块确实存在于 "$env:PSModulePath 位置之一,并且在您运行时会显示:
get-module -listAvailable

我还尝试在 psd1 文件中放入 ModuleName.psm1 文件的完全限定路径。当我这样做(或下面的 x0n 所建议的)时,我得到几乎完全相同的错误:

The module to process 'C:\Powershell\ModuleName\ModuleName.psm1', listed in field 'ModuleToProcess' of module manifest 'C:\Powershell\ModuleName\ModuleName.psd1' was not processed because no valid module was found in any module directory.



在这一点上,我真的不确定去哪里,或者即使这实际上是可能的。我到处搜索,发现了一些看似相关的东西,但从来都不完全相同,往往是我已经克服或(据我所知)还没有遇到的问题。任何帮助,将不胜感激!谢谢!

最佳答案

我怀疑你需要做两件事:

  • 使用 .psd1 的绝对路径文件:否则只能在 $env:PSModulePath 中找到模块将被考虑(执行加载的脚本在哪里运行并不重要)。
  • 确保您可以加载远程脚本。默认或 RemoteSigned除非签名,否则执行策略将阻止远程脚本。
  • 关于c# - 在 C# 运行空间中的远程服务器上导入 Powershell 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831617/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com