厨师 powershell 命令不起作用

chef powershell command doesn't work

我正在尝试获取 ACL 并解析到数组 reg_perms,代码在没有 Where-Object{($_.IdentityReference -eq "BUILTIN\Users")

的情况下工作正常
command ='powershell "(Get-Acl \'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\').Access | Where-Object{($_.IdentityReference -eq "BUILTIN\Users")} | Format-List RegistryRights,AccessControlType,IdentityReference"'

    data = ::Mixlib::ShellOut.new(command).run_command.stdout.strip.gsub(/\r\n?/, "\n")
    reg_perms = data.split("\n\n").each_with_object([]) do |set, arr|
      arr << set.split("\n").map do |f|
        f.split(':').collect(&:strip)
      end.to_h
    end

您对整个字符串使用了单引号:'。然后,当您的字符串用双引号评估时, BUILTIN\Users 字符串周围的双引号不会转义,这意味着您需要以 powershell 方式转义 ""BUILTIN\Users"" 周围的双引号或使用单引号 \'BUILTIN\Users\' 并以 ruby 方式转义它们。

这应该有效:

command ='powershell "(Get-Acl \'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\').Access | Where-Object{
    ($_.IdentityReference -eq \'BUILTIN\Users\')
} | Format-List RegistryRights,AccessControlType,IdentityReference"'

您正在尝试将 "BUILTIN\Users" - 双引号字符串 - 嵌入到您传递给 PowerShell 可执行文件 (powershell "...") 的整个双引号命令字符串中,这是行不通的, 因为 在带引号的字符串中嵌入相同类型的引号需要 转义.

PowerShell,当通过其 CLI (powershell.exe) 从 外部 调用时,需要 embedded " 个字符。 \"-转义(即使使用 PowerShell-内部`""")。 [1]

由于您在Ruby(Chef)端(command = '...')使用引号,转义内部 嵌入 " 个字符。因为 \" 为了 PowerShell 就足够了。

因此,将-eq "BUILTIN\Users"替换为-eq \"BUILTIN\Users\";即:

command ='powershell "(Get-Acl \'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\').Access | Where-Object{($_.IdentityReference -eq \"BUILTIN\Users\")} | Format-List RegistryRights,AccessControlType,IdentityReference"'

或者 - 假设您引用的字符串的 contentliteral你可以在PowerShell命令中使用引号围绕BUILTIN\Users;但是,在那种情况下,因为在 Ruby 方面您对整个命令使用单引号,所以 您需要将嵌入的 ' 实例转义为 \' Ruby的好处:

因此,将-eq "BUILTIN\Users"替换为-eq \'BUILTIN\Users\';即:

command ='powershell "(Get-Acl \'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\').Access | Where-Object{($_.IdentityReference -eq \'BUILTIN\Users\')} | Format-List RegistryRights,AccessControlType,IdentityReference"'

[1] 从 cmd.exe 调用 PowerShell CLI 时 - 从命令提示符、批处理文件或通过 Chef/Ruby - 转义文字 " as "" sometimes ,但并不总是有效(try
powershell -Command "'Nat ""King"" Cole'" 直接从 cmd.exe 命令提示符)。
相反,\"-转义是安全的选择。
`"-转义,这是 典型 PowerShell-内部 转义 " 内部 "..." 的方式, 从不 在这种情况下有效。