public/Out-Json.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


function Out-Json () {
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param(
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Object] $InputObject,

        [Alias("o", "dest")]
        [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $Destination,

        [int32] $Depth = 10,

        [Switch] $Compress,

        [Switch] $Force 
    )

    Process {
        
        $Path = [IO.Path]::GetFullPath($Destination)

        if ($PSCmdlet.ShouldProcess("InputObject", "Writing JSON to $Path")) {
            $dir = Split-Path $Path 
            $createDirectory = $Force.ToBool()
            $directoryExists = [IO.Directory]::Exists($dir)
            if(!$createDirectory -and !$directoryExists) {
                throw [IO.DirectoryNotFoundException] $dir 
            }

            if(!$directoryExists) {
                New-Item $dir -ItemType Directory | Write-Debug 
            }
            
            $json = $null;
            if(!($InputObject -is [String])) {
                if($InputObject -is [array]) {
                    $json = ConvertTo-Json ([array]$InputObject) -Depth $Depth -Compress:$Compress
                } else {

                    $json =  ConvertTo-Json $InputObject -Depth $Depth -Compress:$Compress
                }
            } else {
                $json = [string] $InputObject
            }
            
            # defaults to UTF8 with no Byte Order Mark ("BOM")
            [IO.File]::WriteAllText($Path, $json)
        }
    }
}