Skip to content

Instantly share code, notes, and snippets.

@ngbrown
Last active May 22, 2020 16:42
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 ngbrown/c78b605ab86f2d94a861 to your computer and use it in GitHub Desktop.
Save ngbrown/c78b605ab86f2d94a861 to your computer and use it in GitHub Desktop.
PowerShell scripts
# Import-Module .\FileNameUtils.psm1
function Rename-FilesToSHA {
[CmdletBinding()]
Param(
[ValidateScript({ Test-Path $_ })]
$Path
)
$hasher = [System.Security.Cryptography.HashAlgorithm]::Create('SHA1')
$files = Get-ChildItem $Path -Recurse | Where-Object {-not $_.PSIsContainer}
foreach ($file in $files) {
$hasMatch = $file.Name -match '(.+?)(\.[a-f0-9]{8})?(\.[^\.]*)$'
if ($hasMatch)
{
$fs = New-Object IO.FileStream($file.FullName, 'Open')
$sb = New-Object System.Text.StringBuilder
[void]$sb.Append($Matches.1)
[void]$sb.Append('.')
$hasher.ComputeHash($fs) | Select-Object -First 4 | ForEach-Object { [void]$sb.Append($_.ToString("x2")) }
[void]$sb.Append($Matches.3)
$fs.Close()
$file | Rename-Item -NewName $sb.ToString()
}
}
}
Function Where-Wildcard
{
Param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$false )] [string]$FilterString,
[Parameter(ValueFromPipeline=$true)] [System.IO.FileSystemInfo]$input
)
$match = ([Regex]::Escape($FilterString) -replace '\\\*\\\*', '{dir_wildcard}' -replace '\\\*', '{file_wildcard}' -replace '{dir_wildcard}', '.*' -replace '{file_wildcard}', '[^\\/]*') + '$'
$input | ? { $_.FullName -imatch $match }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment