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

时间:2013-11-25 14:19:44

标签: 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()

2 个答案:

答案 0 :(得分:4)

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

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

new1.AddParameter("Scriptblock", ScriptBlock.Create(file));

答案 1 :(得分:0)

我有一篇文章描述了在http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/从.NET通过WinRM运行Powershell的简单方法。

如果你想复制它,代码就在一个文件中,它也是一个包含对System.Management.Automation的引用的NuGet包。

它可以自动管理可信主机,可以运行脚本块,还可以发送文件(这些文件并非真正支持,但我创建了一个解决方案)。返回始终是Powershell的原始对象。

// this is the entrypoint to interact with the system (interfaced for testing).
var machineManager = new MachineManager(
    "10.0.0.1",
    "Administrator",
    MachineManager.ConvertStringToSecureString("xxx"),
    true);

// for your specific issue I think this would be easier
var results = machineManager.RunScript(
    File.ReadAllText("C:\\LocalWindows.ps1"));

// will perform a user initiated reboot.
machineManager.Reboot();

// can run random script blocks WITH parameters.
var fileObjects = machineManager.RunScript(
    "{ param($path) ls $path }",
    new[] { @"C:\PathToList" });

// can transfer files to the remote server (over WinRM's protocol!).
var localFilePath = @"D:\Temp\BigFileLocal.nupkg";
var fileBytes = File.ReadAllBytes(localFilePath);
var remoteFilePath = @"D:\Temp\BigFileRemote.nupkg";
machineManager.SendFile(remoteFilePath, fileBytes);

如果有帮助,请标记为答案。我的自动部署已经使用了一段时间了。如果您发现问题,请留下评论。