powershell - 输出文件保持为空
问题描述
我有一个包含所有服务器的 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初学者)
解决方案
看起来$serverList
可能包含一个或多个空行,从而导致您看到的错误。
Where-Object
您可以在foreach()
循环声明中过滤掉空行和仅包含空格的行:
$output = foreach ($s in $ServerList |Where-Object {$_.Trim() -ne ''}){
# ...
}
该String.Trim()
方法将删除任何前导和尾随空白字符,因此如果$_.Trim()
等于一个空字符串''
,那么我们知道原始必须已经是一个空字符串或所有空格。运算符-ne
表示不相等。
推荐阅读
- spring-batch - 如何使用 java config 获取 MultiResourceItemReader 的当前资源
- java - 解析后对 Groovy 扁平化的 JsonSluper 对象进行排序
- reactjs - 使用 Expo 时如何在 IOS 和 Android 上使用谷歌地图
- firebase - 具有多重身份验证的 Firebase 身份验证
- amazon-web-services - 使用 sigv4 进行身份验证的 API 网关给出“消息:缺少身份验证令牌”
- ios - 更新后 UITableView 的 numberOfRowsInSection 中的 return 语句崩溃
- javascript - 我可以在 quill 中获取当前可见文本的事件吗?
- redis - 增加 Redis 排序集中的成员
- android - 召回 CallBack(); 需要使用时的功能
- react-native - React Native - 如果我在 React Native 中隐藏警告可以吗?