简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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