Forum Discussion

Fromelard's avatar
Fromelard
Steel Contributor
Jun 24, 2021

Azure DevOps - How to modify files during a Build Pipeline execution based on PowerShell

Azure DevOps Build Pipeline can provide several option, but sometime we need to change a part of content extracted from Source code management (e.g. Git) before execute another task.

In my case, this case is to comment one specific declaration (#include) placed in couple of JavaScript files.

These lines are understood well by the application server using this code, but not by generic JavaScript parser used for example into SonarQube.

 

So into the Pipeline process, it's only a PowerShell task could be used to do that like following.

In Yaml mode:

 

steps:
- powershell: |
   Write-Host "------------------------------------------------------------"
   Write-Host "Get JS File content containing #include line", $(Agent.WorkFolder)
   Write-Host "------------------------------------------------------------"
   
   $AllJSFIleToManage = Get-ChildItem -Path $(Agent.WorkFolder)\*.js -Recurse -Force  |  Select-String -Pattern "#include " -AllMatches | Foreach {$_.Path} | Select-Object -Unique
   foreach ($MyFile in $AllJSFIleToManage)
   {
      Write-Host "JS File to change -", $MyFile
      
      (Get-Content $MyFile -Encoding UTF8) -replace '#include ', '//#include ' | Set-Content $MyFile 
      Write-Host "JS File changed -", $MyFile 
      Write-Host " -----------------------------------"
   }
   
  displayName: 'PowerShell Script remove specific #Include lines from JS files for Sonar'

 

In Visual Editor mode:

 

When the pipeline is running, it will get the source code from Git and change dynamically only the JS files replacing the blocks found with this "#include" by "//#include" to comment the concerned lines in JavaScript.

The result of this execution in Pipeline log is like following:

 

Into SonarQube the result is visible via the Source Code navigation option:

 

You can adapt this code with your specific case and need, but PowerShell tasks are really powerful when you need to change something before a specific step only during the Pipeline execution.

 

Fabrice Romelard

  • chandra805's avatar
    chandra805
    Copper Contributor
    Go to the pipeline details for your pipeline, and choose Edit. Choose ... and select Triggers. Select YAML, Get sources, and view the Default branch for manual and scheduled builds setting. If you change it, choose Save or Save & queue to save the change.

Resources