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

拟墨画扇 提交于 2020-04-18 05:35:44

问题


I'm able to run puppet bolt command in powershell. In powershell, I got output as below

Started on winrm://remotemachine

Finished on winrm://remotemachine

STDOUT:
RemoteMachineHostName

Successful on 1 target Run on 1 tartget in 3.2 sec

My C# is as below

        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
        }

I tried changing build platform target to x64 in Visual Studio 2019 but it didn't worked.

How to fix above issue

Update 1:

I have used below command in powershell script.

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

回答1:


It seems you cannot input the path of the PowerShell to the method AddScript(). Here is an example that runs the PowerShell script through C#:

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

}

        }

So you can try to read the script out and then input them in the method AddScript().




回答2:


I figured it out that, Visual Studio is calling 32 bit powershell and unable to run bolt commands as bolt module installed on 64 bit powershell.

I have changed project build platform to x64 and build it.

It worked.



来源:https://stackoverflow.com/questions/60977355/powershell-invoke-returning-zero-in-c-sharp-for-bolt-command-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!