Powershell - 使用 Get-Content 接受单个字符串参数或文件列表的脚本

Powershell - Script that accepts single string param or filelist using Get-Content

我无法让 PowerShell 接受命令行上的单个字符串参数输入或接受包含服务器列表的文件作为输入。

我试过 this example 但我无法正常工作。

我也试过使用 param([switch] $FileList)IF 语句没有到达 else 块。

我希望放在一起的是一个脚本,它接受在命令行上传入的单个服务器名称或接受来自文本文件的输入。我非常感谢任何指点!

-编辑,使用下面的 运行 脚本 with/without 参数 returns Run on single server 并且它是相同的 if (($FileList -eq $false)) 使用 Keith Hill 的例子,再次无论我尝试传递脚本什么,输出总是相同的(IF 块永远不会到达 ELSE 块)

-Edit2,第二个代码示例在将单个服务器名称传递给脚本时有效,我的问题是试图让 [Switch] 参数接受文件名并将其传递给代码块foreach 循环。它在 ELSE 行出现以下 Get-EventLog : Invalid value '.\fake.txt' for parameter 'machineName'. 错误。

param([switch] $FileList)
if (($FileList -eq $true)) { "No file list input" }
Else { "Run on single server"}

第二个代码示例

param(
[switch]$FileList,
[string]$server)

if ($FileList -eq $true) {
$list = GC $FileList
foreach ($server in $list){Get-EventLog -ComputerName $server -LogName system | Where-Object {$_.EventID -eq '6005'} | Select TimeGenerated,Message | Select -first 1}#End foreach
}

Else{
Get-EventLog -ComputerName $server -LogName system | Where-Object {$_.EventID -eq '6005'} | Select TimeGenerated,Message | Select -first 1
}

如果您设置为使用 switch 参数,这将无济于事,但如果您只需要一个可以是文件或服务器名称的参数,它就可以了。

param (
   [parameter(Mandatory = $true)] [string]$FileList
)

if (Test-Path $FileList) {
  "File found, do file related commands."
}
Else { "Single server actions." }