我尝试使用以下代码从 C# 运行脚本 localwindows.ps1:
PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machineName", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
String file = "C:\\localwindows.ps1";
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(file);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
}
但出现异常:'术语'C:\localwindows.ps1' 未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。
所以我尝试了以下方法:
PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machineName", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
PSCommand new1 = new PSCommand();
String machinename = "machinename";
String file = "C:\\localwindows.ps1";
new1.AddCommand("Invoke-Command");
new1.AddParameter("computername", machinename);
new1.AddParameter("filepath", file);
powershell.Commands = new1;
Console.WriteLine(powershell.Commands.ToString());
Collection<PSObject> results = powershell.Invoke();
}
我收到错误消息:“找不到路径 'C:\localwindows.ps1',因为它不存在。”
但是使用命令 'Invoke-Command -ComputerName "machineName"-filepath C:\localwindows.ps1' ,从本地计算机的 powershell 在远程计算机中创建一个新帐户。
如何从 C# 调用脚本 localwindows.ps1? 如何通过 C# 执行命令 'Invoke-Command -ComputerName "machineName"-filepath C:\localwindows.ps1'?
脚本localwindows.ps1是
$comp = [adsi]“WinNT://machinename,computer”
$user = $comp.Create(“User”, "account3")
$user.SetPassword(“change,password.10")
$user.SetInfo()
最佳答案
实际上您的调用方式应该有效。但在您的两个示例中,脚本 c:\localwindows.ps1
必须驻留在本地计算机上。在 Invoke-Command 的情况下,它将从本地计算机复制到远程计算机。
如果在 Invoke-Command 的情况下,脚本已经存在于远程计算机上并且您不需要将其复制过来,请删除 FilePath
参数并添加以下内容:
new1.AddParameter("Scriptblock", ScriptBlock.Create(file));
关于c# - 从 C# 调用 powershell 脚本文件 (example.ps1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20195392/