首页 > 解决方案 > 输出文件保持为空

问题描述

我有一个包含所有服务器的 txt 列表。我想要的是以下内容:

此列表中的每个服务器都需要被 ping 通。结果需要保存在文件中。

然而,问题是我不断收到错误消息/空输出文件。

$ServerListFile = "c:\temp\ServerList.txt"    
$ServerList = Get-Content $ServerListFile 
$output = foreach ($s in $ServerList) {
  if (Test-Connection -ComputerName $s -count 1 -Quiet ) {
    "$S is alive"
  }
  else {
    "$S is not responding"
  }
}
Out-File -FilePath "C:\temp\ServerStatus.txt"

此代码给出了错误:

Test-Connection : Cannot validate argument on parameter
'ComputerName'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the co mmand again. At line:5
char:37
+   if (Test-Connection -ComputerName $s -count 1 -Quiet ) { "$S is ali ...
+                                     ~~
    + CategoryInfo          : InvalidData: (:) [Test-Connection], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand

两次。据我了解,该变量$s为空。

但是,这个应该充满c:\temp\ServerList.txt

请对此提供一些见解(powershell初学者)

标签: powershell

解决方案


看起来$serverList可能包含一个或多个空行,从而导致您看到的错误。

Where-Object您可以在foreach()循环声明中过滤掉空行和仅包含空格的行:

$output = foreach ($s in $ServerList |Where-Object {$_.Trim() -ne ''}){
    # ...
}

String.Trim()方法将删除任何前导和尾随空白字符,因此如果$_.Trim()等于一个空字符串'',那么我们知道原始必须已经是一个空字符串或所有空格。运算-ne表示不相等


推荐阅读