PowerShell is Windows' powerful and built-in scripting language. And just as a Linux shell it comes with loads of useful commands . Recently I wanted to minify some JSON code to check how much that would shrink its size. I got some inspiration from StackOverflow and finally came up with the following snippet.
Get-Content yourfile.json | ConvertFrom-Json | ConvertTo-Json -Compress | Out-File yourfile.min.json
So let break down what's happening here. First, the contents of the file that is to be minified have to be read using Get-Content. This content is passed to ConvertFrom-Json, which returns a proper JSON object. The actual magic is done by ConvertTo-Json, which converts that object back to a string but also compresses it courtesy of the -Compress option. Finally, this string is written to a file again using Out-File . And if that last part is omitted the string is printed to the terminal.
I deliberately chose to not use input/output redirection here, but it would work just as well. Obviously there are many other solutions to this problem. I just like this one, as it comes batteries-included on every recent Windows machine 😊.
|||Or cmdlets, as commands are called in PowerShell.|
|||FYI, Out-File also has an encoding option that might come in handy.|