Как я могу регулярное выражение строки, которая написана до сих пор в выводе команды? - PullRequest
0 голосов
/ 08 ноября 2019

Я устанавливаю завершающий шаг при обнаружении ExitCode = 1 или выше с помощью регулярного выражения в том же сценарии PowerShell.

Я загружу это в работу jenkins, где работают другие сторонние программы, которые возвращают Lastexitcode, который Powershell не распознает, поэтому мне нужна функция с регулярным выражением, чтобы найти то, что написано до сих пор, и завершить ее посленайти его.

Я пытался:

[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 

Я ожидаю, что после запуска функции она найдет указанную формулу регулярного выражения во всем сценарии и завершит шаг, но вместо этого ядойти до второго шага и ошибка в том, что он ничего не находит в первую очередь.

Ответы [ 2 ]

0 голосов
/ 08 ноября 2019

# 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()```
0 голосов
/ 08 ноября 2019

Я так думаю, переменная $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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...