簡體   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