如果存在“关键字”,请重新运行批处理文件

时间:2018-07-11 11:18:53

标签: powershell batch-file

如果要在日志中找到特定的关键字,我想创建一个重新运行批处理文件的脚本。我遇到的问题是用于检查文件的功能。当前,当我运行此脚本时,它退出,表示表达式“不匹配”,即使该关键字实际上确实存在于日志文件中。在这种情况下,要检查的日志文件名为“ output.log”,而要匹配的关键字称为“临时”。

$current_date = Get-Date -Format yyyyMMdd
$file_path = "backup_" + $current_date
"checking in directory... --> " + $file_path

$word_to_find = "temporary"
$file_to_check = "output.log"

"Searching for matching expression '" + $word_to_find + "' in file: " + $file_to_check
$containsWord = $file_to_check | %{$_ -match $word_to_find}

if ($containsWord -contains $true) {
    'The expression matches, re-running batch feed.'
    start .\batch_script.bat
} else {
    'The expression does not match. Feed OK.'
}

1 个答案:

答案 0 :(得分:3)

那是因为您首先必须获取日志的内容,所以atm只是将字符串"output.log"与字符串"temporary"进行比较,后者通常会返回值'false'。

如果您想继续尝试,请尝试这样(请记住output.log应该位于运行目录中(而不是像此处使用.\),或者您必须提供日志的完整路径文件):

$current_date = Get-Date -Format yyyyMMdd
$file_path = "backup_"+ $current_date
"checking in directory... --> " + $file_path

$word_to_find="temporary"
$file_to_check=".\output.log"

"Searching for matching expression '" + $word_to_find + "' in file: " + $file_to_check
$containsWord = Get-Content $file_to_check | %{$_ -match $word_to_find}

If ($containsWord -contains $true) {
  'The expression matches, re-running batch feed.'
  start .\batch_script.bat
}
Else {
  'The expression does not match. Feed OK.'
} 

如果您有一些改进,我会这样做:

$current_date = Get-Date -Format yyyyMMdd
$file_path = "backup_"+ $current_date
Write-Host "checking in directory... --> $file_path"

$word_to_find="temporary"
$file_to_check="<fullPathToLog>\output.log"

Write-Host "Searching for matching expression '" + $word_to_find + "' in file:  $file_to_check"

If((Get-Content $file_to_check) -match $word_to_find) {
  'The expression matches, re-running batch feed.'
  start .\batch_script.bat
}
Else {
  'The expression does not match. Feed OK.'
}

这将为您节省foreach和额外的变量。