PowerShell StreamReader-如何等待新文件变为可读文件可读、新文件、文件、PowerShell

2023-09-03 11:34:12 作者:南街遗址

我的脚本通常假定存在一个带有设置的*.txt文件,以帮助其更好地运行。但是,如果该脚本不存在,它会创建一个本地文件来保存这些设置。我意识到在逻辑上没有需要读取此文件,但我想了解为什么我不能。

[void][System.IO.File]::Create($PSFileName)
$ReadPS = New-Object System.IO.StreamReader($PSFileName)

脚本可能(很少)创建文件后,它立即尝试读取该文件,这会生成以下错误:New-Object : Exception calling ".ctor" with "1" argument(s): "The process cannot access the file 'C:TempMyFile.txt' because it is being used by another process."

所以我必须等待文件可用,对吗?然而,简单的开始--睡5秒是行不通的。但如果我用try-Catch将它包装在一个循环中,它每次都能在不到一秒的时间内工作:

[void][System.IO.File]::Create($PSFileName)
$RCount = 0                                                             # if new file created, sometimes it takes a while for the lock to be released. 
Do{
    try{
        $ReadPS = New-Object System.IO.StreamReader($PSFileName)
        $RCount+=100
    }catch{                                                             # if error encountered whilst setting up StreamReader, try again up to 100 times.
        $RCount++
        Start-Sleep -Milliseconds 1                                     # Wait long enough for the process to complete. 50ms seems to be the sweet spot for fewest loops at fastest performance
    }
}Until($RCount -ge 100)
$ReadPS.Close()
$ReadPS.Dispose()
windows powershell下载 windows powershell官方版下载 PC下载网

这太复杂了。为什么文件被锁定的时间是任意的,而且我等待的时间越长,锁定的时间似乎就越长?在文件创建和StreamReader之间是否可以调整或添加任何内容以确保文件可用?

推荐答案

正如评论中已经提到的,您使用的方法确实会在文件上创建锁定,该锁定将一直持续到您调用close/dispose方法或PowerShell会话结束。

这就是为什么您等待的时间越长,您的会话保持打开的时间就越长,文件锁定保持的时间也就越长。

我建议您改用New-Item,这是PowerShell的本机方法。

因为您要创建一个StreamReader对象,所以完成后不要忘记关闭/释放该对象。

New-Item -Path $PSFileName -ItemType File
$ReadPS = New-Object System.IO.StreamReader($PSFileName)

#Stuff

$ReadPS.Close()
$ReadPS.Dispose()
最后,如果出于某种原因您仍然想使用[System.IO.File]::Create($PSFileName),您还需要调用close方法来释放锁。