1

Running this from CMD produces the correct result:

powershell -command "& Get-DiskImage -imagepath C:\\file.vhdx | Get-Disk"
<Here is some stuff regarding VHD>

I want to achieve exactly the same running this from C# (there's no way to run it directly, use some PowerShell related .NET stuff, or something else).

My code is the following:

static void LaunchCommandLineApp()
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.FileName = "powershell";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.RedirectStandardOutput = true;
    startInfo.Arguments = "-command \" & get-diskimage -imagepath C:\\file.vhdx | Get-Disk \"";

    using (Process exeProcess = Process.Start(startInfo)) {
        exeProcess.WaitForExit();
        var out = exeProcess.StandardOutput.ReadToEnd();
    }
}

And in "out" I am getting an error:

Get-Disk : Cannot validate argument on parameter 'Number'. The argument is null. Provide a valid value for the argument, and then try running the command again.

But exactly the same code works in CMD. If I remove "| Get-Disk" from arguments, I will get correct output in "out" from the Get-DiskImage cmdlet.

Also, I have tried to play with curly braces, as other answers suggested - error haven't changed.

What shall I put in "startInfo.Arguments", so my output of "Get-DiskImage" will be correctly piped to the next cmdlet?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Starl1ght
  • 4,422
  • 1
  • 21
  • 49

1 Answers1

1

This is not actually a problem with the difference between running from the command line and from C#. I created a test VHDX and got the same (error) result whether run from C# or the command line, as shown by the OP.

In both cases, omitting the | Get-Disk part showed information about the disk image, which lacked a disk number, which is exactly what Get-Disk was complaining about. I suspect the image needs to be mounted for it to have a disk number.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jazzdelightsme
  • 457
  • 3
  • 14
  • While my image have mounted - for some reason C# (even plain C system() call) both omitting number. So, C# is not guilty. – Starl1ght Apr 02 '19 at 07:38