For reasons I'm starting to regret, I got into the habit of just working with [System.IO.FileInfo]
and now I'm wondering if there is a best practice around avoiding that and just using full names to the file(s) or if there is a different workaround for my current conundrum.
I need to make a lot of my smaller scripts work with powershell.exe
vs. pwsh.exe
because they're going to be used by folks and computers that don't have PowerShell (Core) installed - but every once in a while there arises an issue. This time it is the handling of whatever is returned from Get-ChildItem
and the fact that Windows PowerShell doesn't give you the full path like PowerShell (Core) does. One workaround I have would be to force the full name ($file.FullName
), but that in turn breaks the fact that I'm accustomed to working with System.IO.FileInfo
variables.
So first question without examples: What is the best practice? Should I have been using System.IO.FileInfo
in the first place?
Second question, with examples: Is there a better way to handle this so that Windows PowerShell and PowerShell (Core) act consistently?
Consider the following - at this point I would probably call a function to act on each qualifying input file (using filtering on name or file extension, etc. to get the right set).
PS C:\tmp> Function CustomFunction{
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[System.IO.FileInfo]$inputFile
)
$inputFile.BaseName
$inputFile.DirectoryName
$inputFile.GetType()
"`n`n"
}
PS C:\tmp> (Get-ChildItem -LiteralPath $PWD -File).ForEach({CustomFunction $_})
In PowerShell (Core) - The type System.IO.FileSystemInfo
and the function would work even if the file itself isn't located in the working directory
Another File
C:\tmp
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False FileInfo System.IO.FileSystemInfo
Windows PowerShell is still using a type of System.IO.FileSystemInfo
- but there is definitely something different between them. I'm not sure what "IsSerial" actually checks, but if CustomFunction
were taking action on the files then it won't work if they're not in the working directory.
Another File
C:\tmp
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True FileInfo System.IO.FileSystemInfo
So - what's my best course of action? I like the FileInfo
objects themselves because they have some handy properties like BaseName
, Directory
, DirectoryName
, and Extension
. There are probably also a number of useful methods available that I might be using in my functions.
If I just essentially pass $_.FullName
to the function, then within the function it is a string and I'll need to use Split-Path
among other things to get similar properties that I'm working with