Powershell: All new-objects are not created equal?

Question:

I’m working on some short demo scripts for a presentation on powershell and of course one of my own simple demos has me perplexed. The purpose of this demo is to show different ways to create objects in powershell. Here’s my code:

Simple right? Create two FileInfo objects via different methods and read them. The output shows the files are identical:

However, when Get-Content tries to read the $newfile object, I get the following error:

So I noticed in the error it says PSObject which confuses me because in my ouput it seems $newfile is a FileInfo object. So the next logical thing I figured to do would be to typecast $newfile into type [System.IO.FileInfo]. That yielded the same error, except now instead of PSObject it shows FileInfo as the type. So how is it that I’m getting that error if $file and $newfile appear to be identical and get-content worked on $file? Is there some subtle difference when you use the new-object command?

Answer:

I traced the binding with the object created using New-Object and the problem is that Get-Content couldn’t bind to any properties on the FileInfo info object.

You can check this out with this command:

So when you look at the trace of the one that binds successfully you’ll see that Literal path is bound to the property starting with Microsoft.PowerShell.Core\FileSystem:: which is PsPath. So on closer inspection comparing the object properties when piping to Get-Member you’ll see the one that works has these note properties where as the one created with New-Object does not –

  • PSChildName
  • PSDrive
  • PSIsContainer
  • PSParentPath
  • PSPath
  • PSProvider

Taking a look at the Get-Content cmdlet parameters we can see that LiteralPath has an alias of PsPath:


If you add a property to the New-Object created FileInfo it will work:

Source:

Powershell: All new-objects are not created equal? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply