-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Description
Best practice answers and documentation often refer to .Net methods for file streaming where it concerns performance, e.g. Processing Large Files. But the .Net implementation differs from native PowerShell behavior were it concerns casting expectations and the current directory:
([io.fileinfo]'.\Test.txt').DirectoryName
C:\WINDOWS\system32
(Get-Item '.\Test.txt').DirectoryName
C:\Users\User\MyScripts
Btw. There is currently no accelerator or initiator for files:
[fileinfo]'.\Test.txt'
InvalidOperation: Unable to find type [fileinfo].
Note that [io.fileinfo]'.\Test.txt'
strips the .\
from every member of the object which means if it is used for a parameter type, you can't discover anymore that the path was relative (using a condition as e.g. if ($FilePath.Name.StartsWith('.\')) {...
), which means that you can only use a general string
type for this instead.
Using .net (streaming) methods generally require more coding therefore it often ends up in a separate function.
As a (spoiled) PowerShell engineer, I would expect to be able to do just this (wishful thinking):
Function Stream-File([FileInfo]$FilePath) {
$Stream = [System.IO.StreamReader]$FilePath
# ...
$Stream.Dispose()
}
Stream-File .\Test.txt
This implies at least two things:
- The (PowerShell)
FileInfo
constructor needs to accept a relative path that is than joined to the current path (Join-Path (Get-Location) '.\Test.txt'
) to prevent it expects the file in theC:\WINDOWS\system32
folder and to be accelerated to resolve the following error:
InvalidOperation: Unable to find type [FileInfo].
- The
[FileInfo]
class should automatically cast to other file classes along withSystem.IO.StreamReader
which current results in the following error:
Cannot convert the "C:\Users\User\MyScripts\Test.txt" value of type "System.IO.FileInfo" to type "System.IO.StreamReader".
InvalidOperation: