file IO, is this a bug in Powershell?

前端 未结 4 1064
南笙
南笙 2021-01-11 16:26

I have the following code in Powershell

$filePath = \"C:\\my\\programming\\Powershell\\output.test.txt\"

try
{
    $wStream = new-object IO.FileStream $file         


        
相关标签:
4条回答
  • 2021-01-11 16:55

    When using the New-Object cmdlet and the target type constructor takes in parameters, you should either use the -ArgumentList parameter (of New-Object) or wrap the parameters in parenthesis - I prefer to wrap my constructors with parens:

    # 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 cmdlet online help: http://go.microsoft.com/fwlink/?LinkID=113355

    0 讨论(0)
  • 2021-01-11 17:04

    Yet another way could be to enclose the enums in parens:

    $wStream = new-object IO.FileStream $filePath, ([System.IO.FileMode]::Append), `
        ([IO.FileAccess]::Write), ([IO.FileShare]::Read)
    
    0 讨论(0)
  • 2021-01-11 17:06

    If your goal is to write into a logfile or text file, then you could try the supported cmdlets in PowerShell to achieve this?

    Get-Help Out-File -Detailed
    
    0 讨论(0)
  • 2021-01-11 17:10

    Another way would be to use just the name of the value and let PowerShell cast it to the target type:

    New-Object IO.FileStream $filePath ,'Append','Write','Read'
    
    0 讨论(0)
提交回复
热议问题