我该如何正则表达式到目前为止在命令输出中写入的字符串?

我要在相同 PowerShell脚本中通过正则表达式找到ExitCode = 1或更高版本时设置终止步骤。

我将其上传到jenkins作业中,其中正在运行其他第三方软件,这些软件会返回Lastexitcode,而Powershell无法识别它们,因此我需要一个带有regex的函数来查找到目前为止编写的内容并在找到后终止。

我尝试过:

[regex]::new('ExitCode=[1-9]*[0-9]')
function script:ThrowErrors {
  if ([regex]::new('ExitCode=[1-9]*[0-9]') {
    'erorrrrr'
  }
  if ($env:Terminating -eq 1) {
    throw 'This error is terminating the step.'
  }
}

# ps1 log with steps and written output
# step one
1+2 

'ExitCode=1'
'ExitCode=0'
'ExitCode=10'
$env:Terminating = '1'

ThrowErrors

# step two
2+3 

我希望在运行该函数时,它将在整个脚本中找到指示的regex公式并终止该步骤,但是我到达了第二步,而该错误是它一开始什么都没找到。 / p>

sushe302 回答:我该如何正则表达式到目前为止在命令输出中写入的字符串?

我认为变量$env:Terminating一直都是空的。以下对我有用:

function script:ThrowErrors {
  if ([regex]::new('ExitCode=[1-9]*[0-9]'))
  {
    'erorrrrr'
  }
  if ($env:Terminating -eq 1) {
    throw 'This error is terminating the step.'
  }
}

robocopy.exe ? | Out-Null
$env:Terminating = $LASTEXITCODE
$env:Terminating
ThrowErrors

PS C:\> ThrowErrors
erorrrrr
,

# Global enviroment variable
$env:Terminating = '0'


#Checks for ErrorCode value that has more than 0
#Checks for Terminating value


function script:CheckErrors 
{
  Get-Content -Path Step.log | ForEach-Object -Process {
    $CurrentErrorCode = $_

    switch -regex ($CurrentErrorCode) 
    {
      'ExitCode=[1-9][0-9]?' 
      {
        'Found a high error code'
        if ($Terminating -eq 1) 
        {
          'Terminating is enabled.'
          throw 'Terminated'
        }
        else
        {
          'Terminating is disabled.'
        }
      }
      'ExitCode=0'                
      {

      }
    }
  }
}


# All bellow steps can have parts of build scripts.
# Fake step with no errors.
function script:Step1 
{
  'Running Step1'
  "This step hasn't any errors"
  '1/1'
  1/1
  'ExitCode=0'
}

# Another step that has an error but it won't be terminating.
function script:Step2 
{
  'Running Step2'
  'This step has a non terminating error'
  '1/0'
  1/0
  'ExitCode=1'
}

# Another step that has an error but this time is terminating.
function script:Step3 
{
  'Running Step3'
  'This step has a terminating error'
  '1/0'
  1/0
  'ExitCode=10'
}

# This step is in case of the terminating step is bugged.
function script:Step4 
{
  'Running Step4'
  'End of the process.' 
}


# The actual steps.
# Jenkins job will look like this.

#Set-Location "D:\Build_scripts"
#.\NewErrorHandling.ps1


''
Step1 | Tee-Object -FilePath Step.log
$Terminating = '0'
CheckErrors
''
''
Step2 | Tee-Object -FilePath Step.log
$Terminating = '0'
CheckErrors
''
''
Step3 | Tee-Object -FilePath Step.log
$Terminating = '1'
CheckErrors
''
''
Step4 | Tee-Object -FilePath Step.log
$Terminating = '0'
CheckErrors
''
''

# Cleaner if you use ISE.
$Error.Clear()```
本文链接:https://www.f2er.com/3138922.html

大家都在问