IO file, is this a bug in Powershell?

I have the following code in Powershell

$filePath = "C:\my\programming\Powershell\output.test.txt" try { $wStream = new-object IO.FileStream $filePath, [System.IO.FileMode]::Append, [IO.FileAccess]::Write, [IO.FileShare]::Read $sWriter = New-Object System.IO.StreamWriter $wStream $sWriter.writeLine("test") } 

I keep getting the error:

It is not possible to convert the argument "1" with the value: "[IO.FileMode] :: Append", for "FileStream" to enter "System.IO.FileMode": "It is not possible to convert the value" [IO.FileMode] :: Add "to print "System.IO.FileMode" because the enumeration is invalid. Specify one of the following enumeration values ​​and try again. Possible enumeration values ​​are "CreateNew, Create, Open, OpenOrCreate, Truncate, Add."

I tried the equivalent in C #,

  FileStream fStream = null; StreamWriter stWriter = null; try { fStream = new FileStream(@"C:\my\programming\Powershell\output.txt", FileMode.Append, FileAccess.Write, FileShare.Read); stWriter = new StreamWriter(fStream); stWriter.WriteLine("hahha"); } 

it works great!

What happened to my powershell script? BTW I work on powershell

 Major Minor Build Revision ----- ----- ----- -------- 3 2 0 2237 
+8
source share
5 answers

Another way would be to use only the value name and let PowerShell apply it to the target type:

 New-Object IO.FileStream $filePath ,'Append','Write','Read' 
+19
source

When you use the New-Object and the target type constructor accepts parameters, you should either use the -ArgumentList (New-Object) parameter or enclose the parameters in parentheses - I prefer to enclose my constructors in parses:

 # setup some convenience variables to keep each line shorter $path = [System.IO.Path]::Combine($Env:TEMP,"Temp.txt") $mode = [System.IO.FileMode]::Append $access = [System.IO.FileAccess]::Write $sharing = [IO.FileShare]::Read # create the FileStream and StreamWriter objects $fs = New-Object IO.FileStream($path, $mode, $access, $sharing) $sw = New-Object System.IO.StreamWriter($fs) # write something and remember to call to Dispose to clean up the resources $sw.WriteLine("Hello, PowerShell!") $sw.Dispose() $fs.Dispose() 

New-Object Cmdlets Online Help: http://go.microsoft.com/fwlink/?LinkID=113355

+6
source

Another way to enclose enumerations in parens:

 $wStream = new-object IO.FileStream $filePath, ([System.IO.FileMode]::Append), ` ([IO.FileAccess]::Write), ([IO.FileShare]::Read) 
+2
source

If your goal is to write to a log file or a text file, can you try the supported cmdlets in PowerShell to do this?

 Get-Help Out-File -Detailed 
0
source

Your path will work if you use parentheses when creating a FileStream:

 $wStream = new-object IO.FileStream $filePath([System.IO.FileMode]::Append, [IO.FileAccess]::Write, [IO.FileShare]::Read) 
0
source

All Articles