【发布时间】:2022-01-26 07:32:54
【问题描述】:
在 powershell 中,“Get-Content (filename)”命令在读取锁定为只读模式写入的文件时没有任何问题。
那么为什么我不能使用 PowerShell 中的 .net 函数 ReadAllLines 来做同样的事情呢?我不明白为什么 ReadAllLines() 会比 Get-Contents 更具侵入性?它所做的只是读取文件的内容,然后将其关闭。
无论如何,我更喜欢使用 .net 函数而不是本机 powershell 函数,因为它们不太混乱,除了 ReadAllLine 对于部分锁定的文件无法正常工作......有没有办法让 ReadAllLines .net 在读取部分锁定的文件时与 Get-Content 的工作方式相同...可以读取但锁定写入的文件?
[Collections.Generic.List[string]]$lines = [System.IO.File]::ReadAllLines($file)
诗句:
$arr1 = Get-Content $file
$lines = [Collections.Generic.List[string]]$arr1
【问题讨论】:
-
调用
[System.IO.File]::ReadAllLines($file)时会发生什么?如果抛出错误,请完整发布错误消息 -
使用“1”参数调用“ReadAllLines”的异常:“进程无法访问文件 'C:\Users\wpmoore\Desktop\collins\sandbox\sandbox.vsc.tbwork\out .sim\xsim.log',因为它正被另一个进程使用。”在 H:\tools\scripts\filter_xsimlog.ps1:26 char:1 + [Collections.Generic.List[string]]$lines = [System.IO.File]::ReadAll ... + ~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : IOException
-
Get-Content 没有问题...但是...
-
似乎有人应该向 .net 人员提交一个错误,以重写 readalllines 代码,使其与从 powershell 获取内容的工作相同,并且不会抛出具有部分锁定访问权限的异常......
-
非常有趣。我可以通过之前打开同一个文件的可写流来重现您在使用
ReadAllLines()时遇到的错误 - 但在这种情况下,Get-Content也 对我来说失败了......
标签: .net powershell