
不完全なファイル(つまり、現在ディレクトリにコピーされているファイル)が含まれていてはならないディレクトリからファイルリストを取得する必要があります。
Get-ChildItem を使用して不完全なファイルを除外するにはどうすればよいですか?
答え1
コピーするファイルに対して排他ロックを取得しようとする「テスト」関数を作成できる場合があります。排他ロックが成功した場合、ファイルがまだコピーされていないことを意味します。PowerShell 内では、.Net Framework ライブラリ クラスにアクセスできます。この場合、System.IO ライブラリにあります。サンプル スクリプトの例を以下に示します。これを C:\Temp ディレクトリにコピーし、いくつかのテキスト ファイルを作成します。Microsoft Word またはファイルをロックするプログラム (メモ帳はロックしません) で 1 つ以上のテキスト ファイルを開きます。出力には、ロックされていないすべてのファイルが表示されるはずです。
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"
}