繁体   English   中英

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

[英]To call a powershell script file (example.ps1) from C#

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

我在http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/上有一篇文章介绍了通过WinRM从.NET运行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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM