简体   繁体   English

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

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

I tried running a script localwindows.ps1 from C# using the following Code : 我尝试使用以下代码从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();
                }

But getting exception :'The term 'C:\\localwindows.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. 但是获得异常:'术语'C:\\ localwindows.ps1'不被识别为cmdlet,函数,脚本文件或可操作程序的名称。

So I tried the following : 所以我尝试了以下方法:

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();

     }

I am getting the error : "Cannot find path 'C:\\localwindows.ps1' because it does not exist." 我收到错误:“无法找到路径'C:\\ localwindows.ps1',因为它不存在。”

But using command 'Invoke-Command -ComputerName "machineName" -filepath C:\\localwindows.ps1' ,from powershell in local machine created a new account in the remote machine. 但是使用命令'Invoke-Command -ComputerName'machineName“-filepath C:\\ localwindows.ps1',从本地机器中的powershell创建了一个新帐户在远程机器中。

How to call the script localwindows.ps1 from C#? 如何从C#调用脚本localwindows.ps1? How to execute the command 'Invoke-Command -ComputerName "machineName" -filepath C:\\localwindows.ps1' through C#? 如何通过C#执行命令'Invoke-Command -ComputerName“machineName”-filepath C:\\ localwindows.ps1'?

The script localwindows.ps1 is 脚本localwindows.ps1是

$comp = [adsi]“WinNT://machinename,computer”
$user = $comp.Create(“User”, "account3")
$user.SetPassword(“change,password.10")
$user.SetInfo()

Actually your invocation style should work. 实际上你的调用风格应该有效。 But in both of your examples, the script c:\\localwindows.ps1 must reside on the local computer. 但是在两个示例中,脚本c:\\localwindows.ps1必须驻留在本地计算机上。 In the Invoke-Command case, it will be copied from the local computer to the remote computer. 在Invoke-Command情况下,它将从本地计算机复制到远程计算机。

If, in the Invoke-Command case, the script already exists on the remote computer and you don't need to copy it over, remove the FilePath parameter and add this: 如果在Invoke-Command情况下,脚本已存在于远程计算机上而您不需要将其复制,请删除FilePath参数并添加以下内容:

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

I've got an article that describes an easy way to run Powershell through WinRM from .NET at http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/ . 我在http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/上有一篇文章介绍了通过WinRM从.NET运行Powershell的简单方法。

The code is in a single file if you want to just copy it and it's also a NuGet package that includes the reference to System.Management.Automation. 如果您只想复制它,代码就在一个文件中,它也是一个包含对System.Management.Automation的引用的NuGet包。

It auto manages trusted hosts, can run script blocks, and also send files (which isn't really supported but I created a work around). 它自动管理可信主机,可以运行脚本块,还可以发送文件(实际上并不支持,但我创建了一个解决方案)。 The returns are always the raw objects from Powershell. 返回始终是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);

Please mark as answer if this helps. 如果有帮助,请标记为答案。 I've been using this for a while with my automated deployments. 我的自动部署已经使用了一段时间了。 Please leave comments if you find issues. 如果您发现问题,请留下评论。

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

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