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

use*_*880 9 powershell filestream

我在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")
 }
Run Code Online (Sandbox Code Playgroud)

我一直收到错误:

无法转换参数"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");
    }
Run Code Online (Sandbox Code Playgroud)

它工作正常!

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

Major  Minor  Build  Revision
-----  -----  -----  --------
3      2      0      2237
Run Code Online (Sandbox Code Playgroud)

Sha*_*evy 19

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

New-Object IO.FileStream $filePath ,'Append','Write','Read'
Run Code Online (Sandbox Code Playgroud)

  • 我不敢相信 powershell 无法处理构造函数中的枚举。他们现在使用的是 5.1 版本,但这仍然不起作用! (2认同)

Goy*_*uix 6

当使用New-Objectcmdlet并且目标类型构造函数接受参数时,您应该使用-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()
Run Code Online (Sandbox Code Playgroud)

New-Object cmdlet联机帮助:http://go.microsoft.com/fwlink/?LinkID = 113355

  • 除了充当令牌分隔符之外,PowerShell中数组周围的Parens实际上是无操作的.我避免使用这种语法`new-object <typename>(arg,arg,...)`因为它误导你相信这只是一个C#构造函数,而实际上并非如此.实际上使用`new-object <typename> arg,arg,...`的输入更少.抱歉迂腐,但我回答了很多关于为什么`MyPowerShellFunctionThatTakesThreeParameters(1,2,3)`不起作用的问题.:-) (5认同)

mou*_*sio 6

另一种方法是将枚举括在括号中:

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