如果命令存在,则调用函数,否则写入主机消息

时间:2019-07-10 13:13:39

标签: powershell

我知道您可以使用Get-Command检查cmdlet是否存在。但是,假定您要检查的cmdlet数以百计。作为此存在性检查的一部分,如果cmdlet存在,则将执行该命令(在下面的示例中,调用cmdlet并将结果仅导出到csv)。如果该cmdlet不存在,则会通过Write-Host写入一条消息。下面提供了一个示例。

 if (Get-Command "Get-HostedOutboundSpamFilterPolicy" -errorAction SilentlyContinue)
    {
        Get-HostedOutboundSpamFilterPolicy | Export-Csv "C:\HostedOutboundSpamFilterPolicy.csv" -NoTypeInformation 
    }
    else
    {
        Write-Host "Get-HostedOutboundSpamFilterPolicy Not Found"
    }

是否有可能更有效地编写此代码,以避免丑陋/长的if / else?

1 个答案:

答案 0 :(得分:0)

如果您有命令名称列表,则只需在它们上循环即可:

# Could be $commands = Get-Content commands.txt
$commands = "Get-HostedOutboundSpamFilterPolicy","Get-HostedInboundSpamFilterPolicy","SomeOtherCmdlet"

foreach($commandName in $commands){
  if($command = Get-Command $commandName -ErrorAction SilentlyContinue){
    & $command |Export-Csv "${commandName}.csv"
  }
  else {
    Write-Host "$commandName not found!"
  }
}