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

cmm*_*ser 7 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();
                }
Run Code Online (Sandbox Code Playgroud)

但是获得异常:'术语'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();

     }
Run Code Online (Sandbox Code Playgroud)

我收到错误:"无法找到路径'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()
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 4

实际上你的调用风格应该有效。但在两个示例中,脚本c:\localwindows.ps1必须驻留在本地计算机上。在 Invoke-Command 情况下,它将从本地计算机复制到远程计算机。

如果在 Invoke-Command 情况下,脚本已存在于远程计算机上并且您不需要将其复制过来,请删除参数FilePath并添加以下内容:

new1.AddParameter("Scriptblock", ScriptBlock.Create(file));
Run Code Online (Sandbox Code Playgroud)

  • 使用命令 - pipeline.Commands.AddScript(System.IO.File.ReadAllText(file)); - 效果很好。问题出在脚本上。我使用单引号而不是双引号,它起作用了。 (3认同)