File: powershell_escape.rb

package info (click to toggle)
puppet-module-puppetlabs-stdlib 9.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,448 kB
  • sloc: ruby: 3,522; sh: 46; makefile: 2
file content (31 lines) | stat: -rw-r--r-- 818 bytes parent folder | download
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
# frozen_string_literal: true

# @summary
#   Escapes a string so that it can be safely used in a PowerShell command line.
#
# >* Note:* that the resulting string should be used unquoted and is not intended for use in double quotes nor in single
# quotes.
Puppet::Functions.create_function(:'stdlib::powershell_escape') do
  # @param string
  #   The string to escape
  #
  # @return
  #   An escaped string that can be safely used in a PowerShell command line.
  dispatch :powershell_escape do
    param 'Any', :string
  end

  def powershell_escape(string)
    result = ''

    string.to_s.chars.each do |char|
      result += case char
                when ' ', "'", '`', '|', "\n", '$' then "`#{char}"
                when '"' then '\`"'
                else char
                end
    end

    result
  end
end