Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Renames and moves PSN PKGs into folders
#!/bin/pwsh
if ($PSVersionTable.PSVersion.Major -lt 6)
{
Write-Host "This script requires PowerShell 6.0 or newer"
Write-Host "Trying to restart..."
&pwsh $PSCommandPath
}
$content_id_matcher = [regex]'(?<content_id>(?<service_id>(?<service_letters>\w\w)(?<service_number>\d{4}))-(?<product_id>(?<product_letters>\w{4})(?<product_number>\d{5}))_(?<part>\d\d)-(?<label>\w{16}))'
$pkgs = @(Get-ChildItem *.pkg)
foreach ($pkg in $pkgs)
{
$header = Get-Content -LiteralPath $pkg.FullName -AsByteStream -TotalCount 84 -ReadCount 84
$id = [System.Text.Encoding]::ASCII.GetString($header, 48, 36)
$match = $content_id_matcher.Match($id)
if (-not ($match.Success))
{
Write-Warning "Failed to organize $($pkg.Name) (invalid content id $id)"
continue
}
$product_code = $match.Groups['product_id'].Value
$full_path = $pkg.FullName
if ($pkg.Name -notlike "*$product_code*")
{
$new_name = "$id.pkg"
Write-Host "Renaming $($pkg.Name) to $new_name"
Rename-Item -LiteralPath $pkg.FullName -NewName $new_name
$full_path = Join-Path (Split-Path $pkg.FullName -Parent) $new_name
}
$folder_prefix = "[$product_code]"
$folders = @(Get-ChildItem . -Directory -Filter "$folder_prefix*")
$folder = $folder_prefix
if ($folders.Length -eq 0)
{
Write-Host "Creating folder $folder_prefix"
New-Item $folder_prefix -ItemType Directory | Out-Null
}
else
{
$folder = $folders[0].FullName
}
Write-Host "Moving $(Split-Path $full_path -Leaf) to $(Split-Path $folder -Leaf)"
Move-Item -LiteralPath $full_path -Destination $folder
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment