Wednesday, April 10, 2024

PowerShell: Folder Diff

With a new git repo, I after push the source code and then re-pull to a new local repo. To verify the .gitignore is correct, I diff the original folder containing the source code against the git clone just created. The following PowerShell is what I use to dif the folders:

param(
    [Parameter(Mandatory=$true)]
    [string] $folderSource,
    [Parameter(Mandatory=$true)]
    [string] $folderDestination
)

Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop'
Set-PSDebug -Off
# Set-PSDebug -Trace 1

[int] $exitCodeSuccess = 0

[int] $exitCodeError = 1

[int] $exitCode = $exitCodeSuccess


function Get-RelativeFilePaths {
    param(
        [Parameter(Mandatory=$true)]
        [string] $folderPath
    )

    [string] $resolvedFolderPath = 
        (Resolve-Path -Path $folderPath -ErrorAction Stop).Path + '\'

    return (
        Get-ChildItem `
            -Path $folderPath `
            -Recurse `
            -File `
            -ErrorAction Stop).
            FullName.
                Replace($resolvedFolderPath, '')
}

try {
    [string[]] $sourceFiles = `
                 Get-RelativeFilePaths $folderSource
    [string[]] $destinationFiles = `
                 Get-RelativeFilePaths $folderDestination
    
    Compare-Object `
        -ReferenceObject $sourceFiles `
        -DifferenceObject $destinationFiles `
        -ErrorAction Stop    
}

catch {
    [System.Management.Automation.ErrorRecord] $errorRecord = $PSItem

    $exitCode = $exitCodeError
    Write-Host $errorRecord
    Write-Host `
        "Exception Message: $($errorRecord.Exception.Message), " + `
        "Stacktrace: $($errorRecord.Exception.StackTrace)"
}

return $exitCode

The launch.json is as followings when running from Visual Studio Code:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Compare-Folders",
            "type": "PowerShell",
            "request": "launch",
            "script": "${workspaceRoot}/Compare-Folders.ps1",
            "cwd": "${workspaceRoot}",
            "args": [
                "-FolderSource",
                <source folder>,
                "-FolderDestination",
                <destination folder>
            ]
        }
    ]
}


No comments :

Post a Comment