Matt Hintzke
Matt Hintzke

Reputation: 7984

Some .NET 4.0 Classes in PowerShell do not seem to work

I am creating a powershell script that uses some System.Diagnostics.Process and System.Diagnostics.ProcessStartInfo classes.

These classes work completely fine like this:

$processInfo = new-object System.Diagnostics.ProcessStartInfo

$processInfo.FileName = "dism.exe"
$processInfo.UseShellExecute = $false
$processInfo.RedirectStandardOutput = $true
$processInfo.Arguments = "/Apply-Image /ImageFile:C:\images\Win864_SL-IN-837.wim /ApplyDir:D:\ /Index:1"

$process = new-object System.Diagnostics.Process
$process.StartInfo = $processInfo

However, I also want to use a System.IO.StreamReader class but when I try the EXACT same thing with like this:

$stream = new-object System.IO.StreamReader

or like this

$stream = new-object System.IO.StreamReader $process.FileName

I get the error:

New-Object : Constructor not found. Cannot find an appropriate constructor for type System.IO.StreamReader.
At C:\Users\a-mahint\Documents\Testing\inter.ps1:17 char:21
+ $stream = new-object <<<<  System.IO.StreamReader
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

I have been trying to figure this out for half an hour... what is going on? both Classes are part of .NET 4.0

Upvotes: 4

Views: 6565

Answers (1)

TrueWill
TrueWill

Reputation: 25523

StreamReader doesn't have a no-arg constructor, and you haven't supplied any arguments.

Try it in C#. You'll get

'System.IO.StreamReader' does not contain a constructor that takes 0 arguments

Instead, try

$stream = new-object System.IO.StreamReader "foo.txt"

where foo.txt is an existing file.

Note that it doesn't have a constructor with a parameter of type ProcessStartInfo either, which is why passing $process.StartInfo didn't work. Instead, try passing $processInfo.FileName.

Upvotes: 6

Related Questions