【问题标题】:How to run Powershell on a list of computers如何在计算机列表上运行 Powershell
【发布时间】:2019-05-31 05:39:56
【问题描述】:

我正在尝试在位于c:\1\1.txt 下的名为1.txt 的文件中的纯文本文件(每行1 台计算机)中可用的计算机列表上运行远程命令。

我运行 powershell 脚本时,变量 $comp 正在作为 $comp 运行,而不是更改为计算机名

$computers = Get-Content c:\1\1.txt

foreach ($comp in $computers){
$LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, @{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } } 
echo $LicenseInfo, $comp
}

使用计算机名 $comp 运行 powershell 命令 - 其中 $comp 将在每次循环中更改为 c:\1\1.txt 文件中可用的计算机的另一个名称

【问题讨论】:

  • 嗨,@hal9256,我在运行固定脚本 Select-Object 时遇到了这个问题:找不到接受参数“echo”的位置参数。在 C:\1\999.ps1:4 char:182 + ... 16059f" } | Select-Object PartialProductKey, Description, ProductKeyC ... + ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [ Select-Object], ParameterBindingException
  • (抱歉,格式化代码时,回显出现在同一行而不是下一行)。我已经修复了编辑。
  • 感谢您的帮助。我仍然在循环中获得变量名称 $comp,而不是文件下可用的计算机名称 (c:\1\1.txt)。我错过了什么?

标签: powershell powershell-4.0


【解决方案1】:

您收到 Select-Object 错误的原因是 echo 不是 Powershell 中用于批处理的命令。 Powershell使用Write-Host这里有更多信息: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-host?view=powershell-4.0
至于将分隔符开关添加到 get-content 的代码将分隔每个计算机名称

Get-Content -Path c:\1\1.txt -Delimiter `r

`r 代表回车

【讨论】:

    【解决方案2】:

    根据你想要的输出,你可以这样尝试:

    foreach ($comp in $computers) {
    
        $LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, @{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } }
    
        $LicenseInfo
        $comp
    
    }
    

    您在代码中遇到的positional parameter 错误是因为您提供了echo 变量和文本,而文本没有用引号括起来。

    如果你只想输出变量的内容,这里不需要echo 甚至Write-Host

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 2014-01-01
      • 2014-07-26
      • 2022-10-14
      • 2020-09-07
      • 2020-10-13
      • 2019-12-03
      • 2018-02-10
      相关资源
      最近更新 更多