Search code examples
azure-powershellazure-pipelines-yaml

How can you write an inline Powershell@2 task script with if condition?


I've got a yaml pipeline with a task like this:

- task: PowerShell@2
      displayName: Restart my service
      inputs:
        targetType: 'inline'
        script: |
          $service = Get-Service | Where-Object{$_.DisplayName -like "My Service"}
          if($service)
          {
            Write-host $service.Name " service is restarting."
            Restart-Service $service
          }

However, the last '}' is being flagged as an error with "cannot read a block mapping entry". I assume that it's trying to read some of the script as pipeline stuff and doesn't consider it part of the script. How do I get this to be accepted as the whole inline script?


Solution

  • Looks like this was an indenting issue. I got it to work with the following:

    if($service) {
      Write-host $service.Name " service is restarting."
      Restart-Service $service
      }