写这小部分代码来检查文件是否存在并包含字符串模式
try {
$SEL = Select-String -Path \\$serversPing\c$\Scripts\compare_result.txt -Pattern "no differences encountered" -ErrorAction SilentlyCOntinue
}catch{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
}
Finally {
if ($SEL | Test-Path -ErrorAction SilentlyContinue){
#write-host $serversPing $SEL.Pattern
#write-host $serversPing $SEL
if ($SEL.Pattern -eq "no differences encountered")
{
$SoftCheckResult = "ok"
}
else
{
$SoftCheckResult ="Verify"
}
}
else{
$SoftCheckResult = "NotInScope"
}
}
但是,它没有执行应有的操作。首先,它部分识别路径存在,其次部分识别txt文件中的模式。你能帮我么?
我怀疑PATTER服务器上的PATTER可以部分识别。(whitepaces等),甚至如何跳过呢?
奇怪的是,它没有看到文件中缺少该模式,而是返回了 而不是NotinScope验证 下面的文件没有这种模式
在下面您可以看到正常模式
答案 0 :(得分:1)
由于您在$serversPing
中使用了复数形式,因此我怀疑此变量来自代码的较早部分,并且包含服务器的集合。
我将更改检查顺序,并从测试开始,以查看该服务器上是否存在该文件:
# As you mentioned a possible whitespace problem the pattern below uses regex `\s+` so multiple whitespace characters are allowed betwen the words.
$pattern = "no\s+differences\s+encountered"
foreach ($server in $serversPing) {
if (Test-Connection $server -Count 1 -Quiet) {
$filePath = Join-Path -Path "\\$server" -ChildPath 'c$\Scripts\compare_result.txt'
if (Test-Path $filePath -PathType Leaf) {
# -Quiet: Indicates that the cmdlet returns a Boolean value (True or False), instead of a MatchInfo object.
# The value is True if the pattern is found; otherwise, the value is False.
if (Select-String -Path $filePath -Pattern $pattern -Quiet) {
Write-Host "Pattern '$pattern' found in '$filePath'"
$SoftCheckResult = "ok"
}
else {
Write-Host "Pattern '$pattern' not found in '$filePath'"
$SoftCheckResult = "Verify"
}
}
else {
Write-Host "File '$filePath' not found"
$SoftCheckResult ="NotInScope"
}
}
else {
Write-Host "Server '$server' is off-line."
$SoftCheckResult ="OffLine"
}
}
我在foreach循环中添加了Test-Connection
,以首先查看服务器是否在线。如果您之前已检查过该变量,并且$serversPing
变量仅包含联机且可访问的服务器,则可以跳过该服务器。
答案 1 :(得分:0)
关于Select-String cmdlet的-Path,应将值放在“”之间:
$SEL = Select-String -Path "\\$serversPing\c$\Scripts\compare_result.txt" -Pattern "no differences encountered" -ErrorAction SilentlyCOntinue
编辑
这应该可以解决问题:
try {
$SEL = Select-String -Path \\$serversPing\c$\Scripts\compare_result.txt -Pattern "no differences encountered" -ErrorAction SilentlyCOntinue
}catch{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
}
Finally {
if ($SEL){
$SoftCheckResult = "ok"
}
else
{
$SoftCheckResult ="Verify"
}
}
答案 2 :(得分:0)
请尝试如下操作:
$SEL = "Fiile path location"
if ($SEL | Test-Path -ErrorAction SilentlyContinue){
if ($SEL Get-Content | Select-String -pattern "no differences encountered")
{
}
....
}
答案 3 :(得分:0)
try
{
$SEL = $null
$SEL = Select-String -Path \\$serversPing\c$\Scripts\compare_result.txt -Pattern "no differences encountered" -ErrorAction Stop
if ($SEL)
{
$SoftCheckResult = "ok"
}
else
{
$SoftCheckResult = "Verify"
}
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
$SoftCheckResult = "NotInScope"
}
return $softCheckResult