文件IO,这是Powershell中的一个错误吗?

问题描述 投票:8回答:4

我在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")
 }

我一直收到错误:

无法转换参数“1”,值为:“[IO.FileMode] :: Append”,“FileStream”键入“System.IO.FileMode”:“无法转换值”[IO.FileMode] :: Append“to键入“System.IO.FileMode”,因为枚举值无效。请指定以下枚举值之一,然后重试。可能的枚举值为“CreateNew,Create,Open,OpenOrCreate,Truncate,Append”。“

我试过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");
    }

它工作正常!

我的powershell脚本出了什么问题?顺便说一下,我在PowerShell上运行

Major  Minor  Build  Revision
-----  -----  -----  --------
3      2      0      2237
powershell filestream
4个回答
19
投票

另一种方法是只使用值的名称,让PowerShell将其转换为目标类型:

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

6
投票

当使用New-Object cmdlet并且目标类型构造函数接受参数时,您应该使用-ArgumentList参数(New-Object)或将参数包装在括号中 - 我更喜欢用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在线帮助:http://go.microsoft.com/fwlink/?LinkID=113355


2
投票

还有另一种方法可以将枚举包含在parens中:

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

0
投票

如果您的目标是写入日志文件或文本文件,那么您可以尝试使用PowerShell中支持的cmdlet来实现此目的吗?

Get-Help Out-File -Detailed
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.