问题
Imagine that I have a shared folder MyShared:
User A, gets the file \MyShared:\Foo.txt after every 30 seconds.
And I overwrite \MyShared:\Foo.txt also after every 28 seconds (within my PowerShell script)
How can I prevent myself to overwrite this file while the user is getting it, in PowerShell? (I do not want to break the content of the file or end-up with some error by attempting to overwrite it in the time of user retrieving it)
If I rephrase the question: How can I force a Powershell script to wait overwriting a file until another process is finished reading it?
回答1:
In some cases, you may not be able to overwrite it if the file is open.
Otherwise, you will have to devise some other mechanism to signal that the reader has finished reading it. This is not really related to powershell. For example, the reader can create a "lock file" to notify the writer that the file is being read, which it deletes after completing the read. The powershell script can delete the file if the lock file does not exist.
回答2:
I use this function to test if file il locked, but in file txt opened by notepad for example the file isn't locked:
function Test-FileLock {
param (
[parameter(Mandatory=$true)]
[string]$Path
)
$oFile = New-Object System.IO.FileInfo $Path
if ((Test-Path -Path $Path) -eq $false)
{
$false
return
}
try
{
$oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
if ($oStream)
{
$oStream.Close()
}
$false
}
catch
{
# file is locked by a process.
$true
}
}
回答3:
You can use the static Open method in the System.IO.File class. If you try open a file and it is being used by another process it will throw an exception, if you wrap it in a try/catch block, you will be able to tell if an exception has been thrown and therefore return $true in the catch block which will mean its in use.
function Get-FileStatus([string]$Path)
{
try
{
[System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
return $false
}
catch
{
return $true
}
}
if((Get-FileStatus -Path "C:\myfile.bin"))
{
Write-Host "File in Use"
}
else
{
Write-Host "File Not in Use"
}
来源:https://stackoverflow.com/questions/13738236/how-can-i-force-a-powershell-script-to-wait-overwriting-a-file-until-another-pro