c# - 从 C# 调用 powershell 脚本文件 (example.ps1)

标签 c# powershell powershell-remoting

我尝试使用以下代码从 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/

相关文章:

c# - WCF - NetMsmqBinding 与 NetTcpBinding

powershell - 发送带有已在批处理文件中输入的凭据的电子邮件

windows - Powershell 远程处理 : Cannot connect to Windows 2012 EC2 Instance

powershell.exe 命令行变量

powershell - docker机器在创建时卡住了

powershell - 本地语句输出与调用命令输出非常不同

powershell - 从PowerShell运行控制台EXE:本地和远程 session 中输出的不同行为

c# - 如何将方法注入(inject) .Net Framework 中的自动属性

c# - 自适应卡 : Dynamically show Card on dropdown click in Adaptive Card : Bot Builder

c# - 自定义查询结果