Powershellで、ディレクトリが空かどうかをテストするにはどうすればよいですか?
16 に答える
非表示ファイルまたはシステムファイルに関心がない場合は、Test-Pathを使用することもできます
ディレクトリにファイルが存在するかどうかを確認するには、.\temp
次を使用できます。
Test-Path -Path .\temp\*
またはまもなく:
Test-Path .\temp\*
これを試して...
$directoryInfo = Get-ChildItem C:\temp | Measure-Object
$directoryInfo.count #Returns the count of all of the objects in the directory
の場合$directoryInfo.count -eq 0
、ディレクトリは空です。
c:\ Temp(時間がかかる可能性があります)の下の各ファイルの列挙を防ぐために、次のようなことを行うことができます。
if((Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0)
{
# folder is empty
}
filter Test-DirectoryEmpty {
[bool](Get-ChildItem $_\* -Force)
}
1行:
if( (Get-ChildItem C:\temp | Measure-Object).Count -eq 0)
{
#Folder Empty
}
シンプルなアプローチ
if (-Not (Test-Path .\temp*)
{
#do your stuff here
}
-Not
ファイルが存在するときに「if」を入力したい場合は削除できます
このメソッド.GetFileSystemInfos().Count
を使用して、ディレクトリの数を確認できます。Microsoft Docs
$docs = Get-ChildItem -Path .\Documents\Test
$docs.GetFileSystemInfos().Count
JPBlancに追加するだけで、ディレクトリパスが$ DirPathの場合、このコードは角括弧文字を含むパスでも機能します。
# Make square bracket non-wild card char with back ticks
$DirPathDirty = $DirPath.Replace('[', '`[')
$DirPathDirty = $DirPathDirty.Replace(']', '`]')
if (Test-Path -Path "$DirPathDirty\*") {
# Code for directory not empty
}
else {
# Code for empty directory
}
すべてのファイルとディレクトリを取得し、それらをカウントしてディレクトリが空かどうかを判断するのは無駄です。.NETを使用する方がはるかに良いEnumerateFileSystemInfos
$directory = Get-Item -Path "c:\temp"
if (!($directory.EnumerateFileSystemInfos() | select -First 1))
{
"empty"
}
#################################################
# Script to verify if any files exist in the Monitor Folder
# Author Vikas Sukhija
# Co-Authored Greg Rojas
# Date 6/23/16
#################################################
################Define Variables############
$email1 = "yourdistrolist@conoso.com"
$fromadd = "yourMonitoringEmail@conoso.com"
$smtpserver ="mailrelay.conoso.com"
$date1 = get-date -Hour 1 -Minute 1 -Second 1
$date2 = get-date -Hour 2 -Minute 2 -Second 2
###############that needs folder monitoring############################
$directory = "C:\Monitor Folder"
$directoryInfo = Get-ChildItem $directory | Measure-Object
$directoryInfo.count
if($directoryInfo.Count -gt '0')
{
#SMTP Relay address
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#Mail sender
$msg.From = $fromadd
#mail recipient
$msg.To.Add($email1)
$msg.Subject = "WARNING : There are " + $directoryInfo.count + " file(s) on " + $env:computername + " in " + " $directory
$msg.Body = "On " + $env:computername + " files have been discovered in the " + $directory + " folder."
$smtp.Send($msg)
}
Else
{
Write-host "No files here" -foregroundcolor Green
}
空のフォルダを削除する例:
IF ((Get-ChildItem "$env:SystemDrive\test" | Measure-Object).Count -eq 0) {
remove-Item "$env:SystemDrive\test" -force
}
$contents = Get-ChildItem -Path "C:\New folder"
if($contents.length -eq "") #If the folder is empty, Get-ChileItem returns empty string
{
Remove-Item "C:\New folder"
echo "Empty folder. Deleted folder"
}
else{
echo "Folder not empty"
}
#Define Folder Path to assess and delete
$Folder = "C:\Temp\Stuff"
#Delete All Empty Subfolders in a Parent Folder
Get-ChildItem -Path $Folder -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
#Delete Parent Folder if empty
If((Get-ChildItem -Path $Folder -force | Select-Object -First 1 | Measure-Object).Count -eq 0) {Remove-Item -Path $CATSFolder -Force -Recurse}
Get-ChildItemからカウントを取得すると、空のフォルダーまたはフォルダーへのアクセスエラーによってカウントが0になる可能性があるため、誤った結果が得られる可能性があります。
空のフォルダをチェックする方法は、エラーを分離することです。
Try { # Test if folder can be scanned
$TestPath = Get-ChildItem $Path -ErrorAction SilentlyContinue -ErrorVariable MsgErrTest -Force | Select-Object -First 1
}
Catch {}
If ($MsgErrTest) { "Error accessing folder" }
Else { # Folder can be accessed or is empty
"Folder can be accessed"
If ([string]::IsNullOrEmpty($TestPath)) { # Folder is empty
" Folder is empty"
}
}
上記のコードは、最初にフォルダへのアクセスを試みます。エラーが発生した場合は、エラーが発生したことを出力します。エラーがなかった場合は、「フォルダにアクセスできます」と記載し、次に空かどうかを確認します。
既存の回答のいくつかを調べて少し実験した後、私はこのアプローチを使用することになりました。
function Test-Dir-Valid-Empty {
param([string]$dir)
(Test-Path ($dir)) -AND ((Get-ChildItem -att d,h,a $dir).count -eq 0)
}
これにより、最初に有効なディレクトリ(Test-Path ($dir)
)がチェックされます。d
次に、それぞれ属性、、、h
およびによるディレクトリ、隠しファイル、または「通常の」ファイル**を含むコンテンツをチェックしますa
。
使用法は十分に明確である必要があります:
PS C_\> Test-Dir-Valid-Empty projects\some-folder
False
...または代わりに:
PS C:\> if(Test-Dir-Valid-Empty projects\some-folder){ "empty!" } else { "Not Empty." }
Not Empty.
**実際には、の定義された効果a
がここにあるかどうかは100%わかりませんが、いずれにせよ、すべてのファイルが含まれるようになります。ドキュメントにah
は隠しファイルが表示されていると記載されておりas
、システムファイルを表示する必要があると思います。したがって、a
それ自体は「通常の」ファイルを表示しているだけだと思います。上記の関数から削除すると、どのような場合でも隠しファイルは検出されますが、他のファイルは検出されません。
GetFileSystemInfos().Count
テストでも使用することにより、配管用の1つのライン:
gci -Directory | where { !@( $_.GetFileSystemInfos().Count) }
アイテムがないすべてのディレクトリが表示されます。結果:
Directory: F:\Backup\Moving\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 5/21/2021 2:53 PM Test [Remove]
d----- 5/21/2021 2:53 PM Test - 1
d----- 5/21/2021 2:39 PM MyDir [abc]
d----- 5/21/2021 2:35 PM Empty
括弧を含む名前でエッジケースの問題が発生したため、これを投稿します[ ]
。失敗は、他の方法を使用していて、出力がパイプされてRemove-Item
、角かっこで囲まれたディレクトリ名を見逃した場合でした。