首页 > 解决方案 > 在带有 winrm 的 PowerShell 脚本中使用 ruby​​ 变量

问题描述

编辑: 我想通过虚拟机管理器 PowerShell cmdlet 计算存储容器的文件/文件夹。

我遇到了类似的问题,但仍然在语法上苦苦挣扎。我有一个在远程服务器上执行 PowerShell 脚本的 ruby​​ 脚本。我想在 Powershel 脚本中使用 ruby​​ 变量。例如

path_str = "\\XXX\YYY\" #This is the ruby var

PSoutput = shell.run(" #This part is executing the PS script
            $Files = Get-ChildItem -Recurse -File -Path #{path_str}  | Measure-Object | %{$_.Count}" | stdout

如何在 PS 脚本中使用 ruby​​ 变量 path_str?我努力了

# {path_str}

\" " + path_str + " \"

双引号和单引号

没有什么对我有用。

标签: rubypowershellpowershell-remotingwinrm

解决方案


我认为有几件事会导致这些问题。

  1. #是 powershell 中的保留字符。当您使用 # 时,之后的任何内容都是注释。
  2. 您正在分配Get-ChildItemto的输出$files。shell.run() 将没有输出分配给 PSoutput,因为 cmdlet 的输出被分配给$files.
  3. Get-ChildItem是特定于 powershell 的命令,而不是可以从 shell 中执行的命令行/ dos 命令,而无需先调用 powershell 可执行文件。(这个,我有点怀疑,但很确定它是正确的)。

你可以从红宝石做的是,应该工作,

PSoutput = system("powershell get-childitem -Recurse -File -Path " + #{path_str} + "  | Measure-Object | % {$_.Count}")

命令执行后,您应该在 #path_str 目录下拥有文件总数。


推荐阅读