Invoked PS command to string

439 views Asked by At

Is there way to convert invoked powershell command from C# to string?.

Let's say for example i have something like this:

PowerShell ps = PowerShell.Create();
                    ps.AddCommand("Add-VpnConnection");
                    ps.AddParameter("Name", "VPN_" + ClientName);
                    ps.AddParameter("ServerAddress", VPN_SERVER_IP);
                    ps.AddParameter("AllUserConnection");
                    ps.AddParameter("SplitTunneling", true);
                    ps.AddParameter("TunnelType", "L2tp");

And i would like to save invoked command to log file.

Can i somehow return whole command as string?

2

There are 2 answers

1
Sage Pourpre On

I believe what you want essentially is this.

PowerShell ps = PowerShell.Create();
ps.AddScript($"Add-VpnConnection -Name \"VPN_{ClientName}\" -ServerAddress {VPNServerIP} -AllUserConnection -SplitTunneling -TunnelType L2tp");
ps.Invoke();

The invoke return will contain a collection of PSObject so you can read it and save the information like you want in a log in c#.

1
mklement0 On

Note: This answer does not solve the OP's problem. Instead, it shows how to capture a PowerShell command's output as a string in C#, formatted in the same way that the command's output would print to the display (console), if it were run in an interactive PowerShell session.


Out-String is the cmdlet that produces formatted, for-display representations of output objects as strings, as they would print to the screen in a PowerShell console.

Therefore, you simply need to use another .AddCommand() in order to pipe the output from your Add-VpnConnection call to Out-String:

string formattedOutput;
using (PowerShell ps = PowerShell.Create())
{

  ps.AddCommand("Add-VpnConnection")
    .AddParameter("Name", "VPN_" + ClientName)
    .AddParameter("ServerAddress")
    .AddParameter("AllUserConnection", VPN_SERVER_IP)
    .AddParameter("SplitTunneling", true)
    .AddParameter("TunnelType", "L2tp");

  // Add an Out-String call to which the previous command's output is piped to.
  // Use a -Width argument (column count) large enough to show all data.
  ps.AddCommand("Out-String").AddParameter("Width", 512);

  // Due to use of Out-String, a *single string* is effectively returned,
  // as the only element of the output collection.
  formattedOutput = ps.Invoke<string>()[0];

}

Console.Write(formattedOutput);