我已经写了一个函数来检查一个excel文件是否正在被共享的网络驱动器中的另一个进程/用户使用/锁定,如果使用了,则暂停脚本并持续检查,直到它可用,因为下一个操作是将它移出它的文件夹。但是,当我使用System.IO读取文件时,它无法打开该文件。我已经在我的本地驱动器上测试过了,这确实可以打开文件,但是这在网络驱动器上不起作用吗?
$IsLocked = $True
Function Test-IsFileLocked {
[cmdletbinding()]
Param (
[parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias('FullName','PSPath')]
[string[]]$Path
)
Process {
while($isLocked -eq $True){
If ([System.IO.File]::Exists($Path)) {
Try {
$FileStream = [System.IO.File]::Open($Path,'Open','Write')
$FileStream.Close()
$FileStream.Dispose()
$IsLocked = $False
} Catch {
$IsLocked = $True
echo "file in use, trying again in 10 secs.."
Start-Sleep -s 10
}
}
}
}
} 这就是代码无法在我的函数中拾取/打开excel文件的地方。
$FileStream = [System.IO.File]::Open($Path,'Open','Write')在这里,程序通过网络驱动器中的项目文件夹调用function.Loop,如果项目与模式匹配,则将调用函数来检查文件是否正在使用:
$DirectoryWithExcelFile = Get-ChildItem -Path "Z:\NetworkDriveFolder\"$DestinationFolder = "Z:\DestinationFolder\"$pattern = "abc"
foreach($file in $DirectoryWithExcelFile){
if($file.Name -match $pattern){
Test-IsFileLocked -Path $file
$destFolder = $DestinationFolder+$file.Name
Move-item $file.FullName -destination $destFolder
break
}
}发布于 2019-05-29 11:54:54
您必须将close和dispose放在try的最后部分,这样,如果它抛出异常,它就会释放锁。也不能保证这是一个文件锁异常,所以你最好是throw异常,捕捉你期望的异常或者write it out
$IsLocked = $True
Function Test-IsFileLocked {
[cmdletbinding()]
Param (
[parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias('FullName','PSPath')]
[string]$Path
)
Process {
while($isLocked -eq $True){
If ([System.IO.File]::Exists($Path)) {
Try {
$FileStream = [System.IO.File]::Open($Path,'Open','Write')
$IsLocked = $False
} Catch [System.IO.IOException] {
$IsLocked = $True
echo "file in use, trying again in 10 secs.."
Start-Sleep -s 10
} Catch {
# source https://stackoverflow.com/questions/38419325/catching-full-exception-message
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId
$formatstring -f $fields
write-output $formatstring
} finally {
if($FileStream) {
$FileStream.Close()
$FileStream.Dispose()
}
}
}
}
}
} 编辑:路径应该是字符串,而不是字符串数组,除非您有多个路径,在这种情况下重命名为$Paths并循环通过它们$Paths| % { $Path = $_; #do stuff here }
https://stackoverflow.com/questions/56352753
复制相似问题