Following the thread here I am trying to write to an output file in PowerShell 7.2:
# [String] $csvFile = "output.csv"
[String] $csvFile = ".\output.csv"
$stream = New-Object IO.StreamWriter $csvFile, $true
$stream.WriteLine("Some, text")
$stream.Close()
The file is not created. Also, if I create the file beforehand, the script does not write to it. What am I missing? I can get it to work with Out-File but the streams are large and I prefer the Net approach.
Is it a permissions issue in the shell?
>Solution :
My preferred approach:
# create a new file using the provider cmdlets
$newFile = New-Item -Name output.csv -ItemType File
try {
# open a writable FileStream
$fileStream = $newFile.OpenWrite()
# create stream writer
$streamWriter = [System.IO.StreamWriter]::new($fileStream)
# write to stream
$streamWriter.WriteLine("Some, text")
}
finally {
# clean up
$streamWriter.Dispose()
$fileStream.Dispose()
}
For an existing file, use Get-Item or Get-ChildItem to find the existing file system item.
The advantage of letting the provider cmdlets deal with the file is that you don’t need to worry about qualifying the relative path, .\output.csv will be resolves relative to the current location in the shell