Skip to content

Commit b7fdacf

Browse files
committed
feat(function): Create Compare-FilesWithVSCode function to compare two files using VS Code's diff viewer
1 parent 6587589 commit b7fdacf

File tree

2 files changed

+73
-3
lines changed

2 files changed

+73
-3
lines changed

Snippets/Compare Two Files with Code.ps1

Lines changed: 0 additions & 3 deletions
This file was deleted.
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
function Compare-FilesWithVSCode {
2+
<#
3+
.SYNOPSIS
4+
Opens two files in Visual Studio Code's diff viewer.
5+
6+
.DESCRIPTION
7+
Launches Visual Studio Code with the diff view to compare two files side-by-side.
8+
Requires Visual Studio Code to be installed and accessible via the 'code' command.
9+
10+
.PARAMETER ReferencePath
11+
The path to the reference file (shown on the left in diff view).
12+
13+
.PARAMETER DifferencePath
14+
The path to the difference file (shown on the right in diff view).
15+
16+
.EXAMPLE
17+
Compare-FilesWithVSCode -ReferencePath '~/file1.txt' -DifferencePath '~/file2.txt'
18+
Opens file1.txt and file2.txt in VS Code's diff viewer.
19+
20+
.EXAMPLE
21+
Compare-FilesWithVSCode '~/original.ps1' '~/modified.ps1'
22+
Compares two PowerShell scripts using positional parameters.
23+
24+
.NOTES
25+
Requires Visual Studio Code to be installed and the 'code' command available in PATH.
26+
#>
27+
[CmdletBinding()]
28+
param (
29+
[Parameter(
30+
Mandatory = $true,
31+
Position = 0,
32+
HelpMessage = 'Path to the reference file'
33+
)]
34+
[ValidateScript({
35+
if (-not (Test-Path -Path $_ -PathType Leaf)) {
36+
throw "Reference file does not exist: $_"
37+
}
38+
$true
39+
})]
40+
[string]$ReferencePath,
41+
42+
[Parameter(
43+
Mandatory = $true,
44+
Position = 1,
45+
HelpMessage = 'Path to the difference file'
46+
)]
47+
[ValidateScript({
48+
if (-not (Test-Path -Path $_ -PathType Leaf)) {
49+
throw "Difference file does not exist: $_"
50+
}
51+
$true
52+
})]
53+
[string]$DifferencePath
54+
)
55+
56+
begin {
57+
# Verify VS Code is available
58+
$CodeCommand = Get-Command -Name 'code' -ErrorAction SilentlyContinue
59+
if (-not $CodeCommand) {
60+
throw "Visual Studio Code ('code') not found. Please ensure VS Code is installed and added to PATH."
61+
}
62+
}
63+
64+
process {
65+
try {
66+
# Launch VS Code with diff view
67+
& code --diff $ReferencePath $DifferencePath
68+
}
69+
catch {
70+
Write-Error "Failed to open diff view: $_"
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)