Skip to content

Instantly share code, notes, and snippets.

@metadaddy
Last active December 5, 2022 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metadaddy/12135ebe8db638a6d6cd10623d961aa4 to your computer and use it in GitHub Desktop.
Save metadaddy/12135ebe8db638a6d6cd10623d961aa4 to your computer and use it in GitHub Desktop.
PowerShell script to create a marker file in each empty directory under a given root directory
<# .SYNOPSIS
Create a marker file in each empty directory under a given root directory
.DESCRIPTION
This script recursively finds empty directories under the given root
directory and creates a marker file with the given filename in each one.
.NOTES
Author : Pat Patterson
#>
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory, HelpMessage='Specifies the root directory from which to start.')]
[string]
$RootDirectory,
[Parameter(Mandatory, HelpMessage='Specifies the name of the marker file.')]
[string]
$Filename
)
# Initialize array for marker file paths
$paths = @()
# Recurse from the given root directory
Get-ChildItem -Path $RootDirectory -Recurse |
# Is the item a directory?
? {$_.PSIsContainer -eq $True} |
# Is the directory empty?
? {$_.GetFileSystemInfos().Count -eq 0} |
ForEach-Object {
# Make the marker file path and append it to the array
$path = $_.FullName + "/" + $Filename
$paths += $path
# If the user specified -WhatIf, then display the paths after ShouldProcess
# so we get the 'What if:' output. Otherwise display them before the confirmation
if (!$WhatIfPreference) {
# Output the marker file path
Write-Host "$($path)"
}
}
if ($PSCmdlet.ShouldProcess($RootDirectory)) {
# No -Confirm parameter, or user confirmed
ForEach ($path in $paths) {
# Create the marker file
New-Item -Path $path -ItemType "file" -Confirm:$False | Out-Null
}
} elseif ($WhatIfPreference) {
# User specified -WhatIf
ForEach ($path in $paths) {
# Output the marker file path
Write-Host "$($path)"
}
}
# Wait for confirmation before exiting
Read-Host -Prompt "Press Enter to exit"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment