我在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”,for “FileStream”键入“System.IO.FileMode”:“无法转换值 “[IO.FileMode] :: Append”因无效而输入“System.IO.FileMode” 枚举值。指定以下枚举值之一 然后再试一次。可能的枚举值是“CreateNew,Create, Open,OpenOrCreate,Truncate,追加“。”
我尝试了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
答案 0 :(得分:19)
另一种方法是仅使用值的名称,让PowerShell将其转换为目标类型:
New-Object IO.FileStream $filePath ,'Append','Write','Read'
答案 1 :(得分: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 :(得分:2)
另一种方法可能是将这些词汇包含在parens中:
$wStream = new-object IO.FileStream $filePath, ([System.IO.FileMode]::Append), `
([IO.FileAccess]::Write), ([IO.FileShare]::Read)
答案 3 :(得分:0)
如果您的目标是写入日志文件或文本文件,那么您可以尝试使用PowerShell中支持的cmdlet来实现此目的吗?
Get-Help Out-File -Detailed