我需要能够通过 C# 运行空间针对另一台远程计算机执行驻留在远程计算机上的 PS1 脚本。
要明确我的意思:我正在创建的服务驻留在服务器 A 上。它使用以下方法为服务器 B 创建一个远程运行空间。通过运行空间,我试图针对服务器 B 调用驻留在服务器 C 上的脚本。如果有帮助,当前服务器 A 是服务器 C,但不能保证总是如此。
这是我用来进行远程调用的方法:
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 脚本。例如:
"& \"\\\\remoteserveraddress\\PathToScript\\Install.ps1\" -Parameter;Import-Module Modulename;CustomCommand-FromModule -parameter(s) -ErrorAction stop"
如果我在要运行脚本的远程机器上,在 powershell 控制台中,我可以给出以下命令:
& "\\remoteserverC\PathToScript\Install.ps1" -Parameter
但是,如果我尝试通过 c# 运行空间运行它,这将拒绝为我工作。
如果我将以下内容作为参数发送到“remoteScript”:
"& \"\\\\remoteserverC\\PathToScript\\Install.ps1\" -Parameter"
我收到以下错误:
术语“\remoteserverC\PathToScript\Install.ps1”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。
我尝试过使用和不使用“&”以及使用和不使用参数。我已经可以调用直接驻留在远程计算机上的脚本“c:\...\Install.ps1”而不是“\\remoteserver\...\Install.ps1”,但是如果能够直接调用远程脚本。
我在 google 和 stackoverflow 上搜索了很多页面,但我找不到任何有助于克服这个问题的东西。任何帮助,将不胜感激!谢谢!