簡體   English   中英

Powershell Invoke() 在 C# 中為 bolt 命令運行返回零

[英]Powershell Invoke() returning zero in C# for bolt command run

我可以在 powershell 中運行 puppet bolt 命令。 在powershell中,我得到如下輸出

從 winrm://remotemachine 開始

在 winrm://remotemachine 上完成

STDOUT: RemoteMachineHostName

在 1 個目標上成功在 3.2 秒內在 1 個目標上運行

我的 C# 如下

        PowerShell ps = PowerShell.Create();

        ps.AddScript("C:\\User1\\GetRemoteAzureVMHostName.ps1");

        Collection<PSObject> results =  ps.Invoke();  // in results, I'm getting value as 0.

        foreach (PSObject result in results)
        {
            //Do something
        }

我嘗試在 Visual Studio 2019 中將構建平台目標更改為 x64,但沒有奏效。

如何解決上述問題

更新 1:

我在 powershell 腳本中使用了以下命令。

bolt command run hostname --targets winrm://158.28.0.546 --no-ssl-verify --user testuser123 --password test@84p

似乎您無法將 PowerShell 的路徑輸入到AddScript()方法中。 以下是通過 C# 運行 PowerShell 腳本的示例:

private static string script =File.ReadAllText(@"Path\Sum.ps1");
private static void CallPS1()
{
    using (Runspace runspace = RunspaceFactory.CreateRunspace())
        {
         runspace.Open();

         PowerShell ps = PowerShell.Create();
         ps.Runspace = runspace;
         ps.AddScript(script);
         ps.Invoke();

         foreach (PSObject result in ps.Invoke())
         {
             Console.WriteLine("CallPS1()");
             Console.WriteLine(result);
         }

}

        }

因此,您可以嘗試讀取腳本,然后將它們輸入到AddScript()方法中。

我發現,Visual Studio 正在調用 32 位 powershell,並且無法將 bolt 命令作為安裝在 64 位 powershell 上的 bolt 模塊運行。

我已將項目構建平台更改為 x64 並構建它。

有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM