Skip to content

Instantly share code, notes, and snippets.

@michaeltlombardi
Last active October 1, 2019 18:40
Show Gist options
  • Save michaeltlombardi/6465bdaf9711ed171309b8bb32a018e9 to your computer and use it in GitHub Desktop.
Save michaeltlombardi/6465bdaf9711ed171309b8bb32a018e9 to your computer and use it in GitHub Desktop.
Example demo for ruby-pwsh gem
# frozen_string_literal: true
source 'https://rubygems.org'
gem 'irbtools'
gem 'ruby-pwsh'
gem 'fuubar'
if RUBY_VERSION == "1.8.7"
gem 'debugger'
elsif RUBY_VERSION =~ /^2\.[01]/
gem "byebug", "~> 9.0.0"
gem "pry-byebug"
elsif RUBY_VERSION =~ /^2\.[23456789]/
gem "pry-byebug"
else
gem "pry-debugger"
# gem 'ruby-debug'
end
gem "pry-stack_explorer"
require 'irbtools'
require 'ruby-pwsh'
# The gem includes some helpers for discovering the path
# to the executables for PowerShell on the local machine,
# both Windows PowerShell and xplatform PowerShell (v6+).
Pwsh::Manager.powershell_path
Pwsh::Manager.pwsh_path
# When spinning up an instance of the manager we use the
# instance method instead of new - this will check first
# to see if a prior instance of the manager exists with
# the same path, arguments, and options - if it does, then
# it reuses that instance if it is alive; if it does not
# exist or is broken or otherwise not working, it builds a
# new instance and caches the reference for use.
posh = Pwsh::Manager.instance(Pwsh::Manager.powershell_path,Pwsh::Manager.powershell_args)
# Here we see the uninteresting fact that yes, after about
# a second and a half, we have an instance!
Pwsh::Manager.instances
# But, when we try to instantiate another instance using the
# same path, arguments, and options:
posh2 = Pwsh::Manager.instance(Pwsh::Manager.powershell_path,Pwsh::Manager.powershell_args)
# Not only does it come back almost immediately, but it does
# not spin up a second instance at all!
Pwsh::Manager.instances
# We can, of course, instantiate cross-platform instances of
# the PowerShell manager:
pwsh = Pwsh::Manager.instance(Pwsh::Manager.pwsh_path,Pwsh::Manager.pwsh_args)
# After a second or two, we see there are now two instances of
# the manager loaded and alive:
Pwsh::Manager.instances
# We can run arbitrary commands now against one of the managers:
pp posh.execute('$PSVersionTable.PSVersion')
# And we can interpolate the output directly into strings:
"Version of PowerShell in the posh host: #{posh.execute('$PSVersionTable.PSVersion.Major')[:stdout]}"
"Version of PowerShell in the pwsh host: #{pwsh.execute('$PSVersionTable.PSVersion.Major')[:stdout]}"
# Gracefully exiting the manager is good practice.
posh.exit
pwsh.exit
# After the instances are exited they no longer show up in the list
# and would have to be rebuilt if needed again:
Pwsh::Manager.instances
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment