Skip to content

Instantly share code, notes, and snippets.

@tcartwright
Created January 22, 2025 14:41
Show Gist options
  • Save tcartwright/fe4002f6ed1011f268ac0db4857ede42 to your computer and use it in GitHub Desktop.
Save tcartwright/fe4002f6ed1011f268ac0db4857ede42 to your computer and use it in GitHub Desktop.
POWERSHELL: Sorts a postman collection by names of folders and requests recursively
@rem bat file to ease use of powershell script
@%~d0
@cd "%~dp0"
powershell.exe -ExecutionPolicy RemoteSigned -NoLogo -NonInteractive -NoProfile -file "%~dpn0.ps1" -Path "%~1"
@pause
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string] $Path
)
Clear-Host
$file = [System.IO.FileInfo]::new($Path)
$outputFilePath = [IO.Path]::Combine($file.Directory, "$($file.BaseName)_sorted$($file.Extension)")
# Function to recursively sort a Postman collection by the 'name' property
function Sort-PostmanCollection($obj, $path) {
$itemMember = Get-Member -InputObject $obj -Name "item"
if ($itemMember) {
Write-Output "Sorting $path"
# Sort the 'item' array by 'name'
$obj.item = $obj.item | Sort-Object -Property name
# Recursively sort each item in the 'item' array
foreach ($item in $obj.item) {
Sort-PostmanCollection -obj $item -path "$path/$($item.name)"
}
}
elseif ($obj -is [System.Collections.ArrayList] -or $obj -is [System.Object[]]) {
foreach ($item in $obj) {
Sort-PostmanCollection -obj $item -path "$path/$($item.name)"
}
}
}
# Read and parse the JSON file
$jsonContent = Get-Content -Path $file.FullName -Raw | ConvertFrom-Json
# Sort the collection recursively
Sort-PostmanCollection -obj $jsonContent -path "."
# Save the sorted collection back to a file
$jsonContent | ConvertTo-Json -Depth 100 | Set-Content -Path $outputFilePath
Write-Output "`r`nCollection sorted and saved to $outputFilePath"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment