-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
PrettyPrint-File.ps1
92 lines (77 loc) · 1.85 KB
/
PrettyPrint-File.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<#
.SYNOPSIS
Format or pretty-pretty JSON and XML files.
.PARAMETER Path
The path to the file.
.PARAMETER Dedent
For Json, will strip unwanted extra spaces from the output, mostly.
.PARAMETER Overwrite
Overwrite the input file. Default is to print to the console.
#>
# CmdletBinding adds -Verbose functionality, SupportsShouldProcess adds -WhatIf
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
[string] $Path,
[switch] $Dedent,
[switch] $Overwrite
)
Begin
{
function FormatJson ($filePath)
{
$json = Get-Content $filePath | ConvertFrom-Json | ConvertTo-Json -Depth 100
if ($Dedent)
{
# ConvertTo-Json formatting is verbose so strip unwanted spaces
$json = ($json -split "\r\n" | % `
{
$line = $_
if ($line -match '^ +')
{
$len = $Matches[0].Length / 4
$line = ' ' * $len + $line.TrimStart()
}
$index = $line.IndexOf('": ')
if ($index -gt 0)
{
$line = $line.Replace('": ', '": ')
}
$line
}) -join [Environment]::NewLine
}
if ($Overwrite)
{
$json | Out-File -FilePath $filePath -Force
return
}
$json
}
function FormatXml ($filePath)
{
$null = [Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq")
if ($Overwrite)
{
[Xml.Linq.XElement]::Load($filePath).Save($filePath, [Xml.Linq.SaveOptions]::None)
}
else
{
[Xml.Linq.XElement]::Load($filePath).ToString([Xml.Linq.SaveOptions]::None)
}
}
}
Process
{
$filepath = Resolve-Path $Path -ErrorAction SilentlyContinue
if (!$filepath)
{
Write-Host "Could not find file $Path" -ForegroundColor Yellow
return
}
switch ((Get-Item $filepath).Extension)
{
'.json' { FormatJson $filepath }
'.xml' { FormatXml $filepath }
default { Write-Host 'File must have an extension of either .json or .xml' -ForegroundColor Yellow }
}
}