首页 > 解决方案 > 将从文件中读取的变量传递给调用命令

问题描述

我正在努力使用名称中带有单词“Test”的powershell远程回收所有IIS应用程序池,但也排除了名称中带有Test的几个特定AppPools。我可以通过以下方式在本地进行:

## List of Apppool Names to Exclude
$Exclusions = Get-Content "C:\temp\Recycle TEST app pools Exclusions.txt"

## Load IIS module:
Import-Module WebAdministration

## Restart app pools with test in the name
Get-ChildItem –Path IIS:\AppPools -Exclude $Exclusions | WHERE { $_.Name -like "*test*" } | restart-WebAppPool}

但是,当我使用时,我无法将应用程序池从列表中排除:

$server = 'SERVER01', 'SERVER02'

## List of Apppool Names to Exclude
$Exclusions = Get-Content "C:\temp\Recycle TEST app pools Exclusions.txt"

## Load IIS module:
Import-Module WebAdministration

## Restart app pools with test in the name
invoke-command -computername $server -ScriptBlock {Get-ChildItem –Path IIS:\AppPools -Exclude $args[0] | WHERE { $_.Name -like "*test*" } | restart-WebAppPool}} -ArgumentList $Exclusions

远程计算机上确实存在文件“C:\temp\Recycle TEST app pools Exclusions.txt”,但它也需要吗?如果可以开始工作,列表是否也可以传递给 Invoke-Command?

提前致谢

标签: powershellvariablesiispowershell-remotinginvoke-command

解决方案


虽然将数组作为单个参数传递可能很困难,但您可以在这里利用它,因为无论如何您只有一种参数类型。

invoke-command -computername $server -ScriptBlock {Get-ChildItem –Path IIS:\AppPools -Exclude $args[0] | WHERE { $_.Name -like "*test*" } | restart-WebAppPool}} -ArgumentList $Exclusions

在此,您使用$args[0],但这等效于$Exclusions[0]因为数组中的所有项目都已作为参数传递。

但是,如果它们都作为参数传递......就是这样$args。因此,完全按照您$Exclusions在本地使用的方式使用它。

Invoke-Command `
  -ComputerName $server `
  -ArgumentList $Exclusions `
  -ScriptBlock {
    Get-ChildItem –Path "IIS:\AppPools" -Exclude $args |
      Where-Object Name -like "*test*" |
      Restart-WebAppPool
  }

推荐阅读