Created
January 8, 2026 11:39
-
-
Save skull-squadron/510b087054d4b6237aa711c63aa270d9 to your computer and use it in GitHub Desktop.
Run Powershell stuff on WinDOwS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # frozen_string_literal: true | |
| # vi:ft=ruby | |
| autoload :Base64, 'base64' | |
| autoload :Open3, 'open3' | |
| module Pwsh | |
| extend self | |
| def unfreeze(obj) | |
| ::Marshal.load(::Marshal.dump(obj)) | |
| end | |
| def encode_cmd(cmd) | |
| ::Base64.strict_encode64(cmd.encode('utf-16le')) | |
| end | |
| def output_filter(output) | |
| output.split(/\r?\n/).count > 1 ? output : output.chomp | |
| end | |
| def run(cmd, exe: nil) | |
| exe = 'pwsh.exe' if exe == :pwsh | |
| exe ||= 'powershell.exe' | |
| cmd = encode_cmd(cmd) | |
| output, result = ::Open3.capture2(exe, '-encodedCommand', cmd, err: 'NUL') | |
| result = unfreeze(result) | |
| result.tap { |self_| self_.define_singleton_method(:output) { ::Pwsh.output_filter(output) } } | |
| end | |
| end | |
| ### Example | |
| # if (st = Pwsh.run(%{Get-Uptime | %{$_.TotalSeconds}}, exe: :pwsh)).success? | |
| # puts st.output | |
| # else | |
| # warn 'ERROR' | |
| # exit 1 | |
| # end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment