
我需要從目錄中獲取文件列表,該目錄不得包含不完整的文件(即當前複製到該目錄的文件)
如何讓 Get-ChildItem 排除不完整的檔案?
答案1
您也許可以建立一個「測試」函數,嘗試取得您要複製的檔案的獨佔鎖定。如果排他鎖成功,則表示文件尚未被複製。在 PowerShell 中,您可以存取 .Net Framework 庫類,在本例中可以在 System.IO 庫中找到這些類別。下面是一個可能的範例腳本。將其複製到 C:\Temp 目錄並建立一些文字檔案。使用 Microsoft Word 或某些將鎖定檔案的程式(記事本不會)開啟一個或多個文字檔案。您可能期望輸出是所有未鎖定的檔案。
function Test-UnLockedFile
{
param([string] $fileNameAndPath)
try
{
Write-Host "Test-LockedFile called with $fileNameAndPath"
$fileInfo = New-Object ('System.IO.FileInfo') "$fileNameAndPath"
$fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
$fileStream.Close()
Write-Host "Test-LockedFile found an unlocked file (i.e. `$true)"
$true
}
catch
{
Write-Host "Test-LockedFile found a locked file (i.e. `$false)"
$false
}
}
$files = Get-ChildItem -Path "C:\Temp\" -Exclude *.ps1
$unlockedFiles = $files | Where-Object { Test-UnLockedFile $_.FullName }
foreach ($file in $unlockedFiles)
{
$name = $file.FullName
Write-Host "Found unlocked file at $name"
}