Why is it that in .NET the System.IO.FileInfo
object does not have a BaseName
property, but I can use the property through PowerShell, e.g.:
$FolderItems = Get-ChildItem -Path "C:\" | Where-Object {$_ -isnot [IO.DirectoryInfo]}
foreach ($FolderItem in $FolderItems)
{
write-host $FolderItem.BaseName
}
Powershell adds that property for you. If you run get-member on a fileinfo object, you can see that it's a script property, and even the script itself:
get-item testfile1.txt | Get-Member BaseName | format-list
TypeName : System.IO.FileInfo
Name : BaseName
MemberType : ScriptProperty
Definition : System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remove($this.Name.Length -
$this.Extension.Length)}else{$this.Name};}
Because BaseName isn't a Property, it's a ScriptProperty.
Name MemberType Definition
---- ---------- ----------
BaseName ScriptProperty System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remove($this.Name.Length - $this.Extension.Length)}else{$this.Name};}
To clarify, it is a calculated response that PowerShell gives you derived from other properties of the object. It is not itself a direct property of a System.IO.FileInfo
object. When you ask PowerShell for the BaseName value it looks at the Name value, checks if there is an Extension value, and then truncates the Extension value from the Name value and returns the result.
Edit: Amazing how somebody else answers the question 2 minutes after me with a virtually identical answer and they get twice as many up votes and are marked as the answer. </nerdrage>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With