Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get StreamWriter in PowerShell to create a file and use it?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading