0

I am trying to create a .ps1 file with the Azure YAML pipelines powershell task using an inline script;

- task: PowerShell@2
  displayName: "Create IIS Log Cleardown script file"
  env:
    DaysToKeep: ${{ parameters.DaysToKeep }}
  inputs:
    targetType: 'inline'
    script: |
      $DaysToKeep = $env:DaysToKeep
      Set-Content -Path C:\scripts\CleanupScript.ps1 @"
      $logPath = 'C:\inetpub\logs\LogFiles'
      $daysKept = $DaysToKeep
      $retentionDate = $(Get-Date).AddDays(-$daysToKeep)
      ..."@

On the target server the file is updated however all the powershell variables have been stripped/replaced in the file;

 = 'C:\inetpub\logs\LogFiles'
 = 3
 = .AddDays(-3)

The powershell script variables $logPath, $daysKept and $retentionDate have been removed.

I have tried escaping the script several ways with no luck, is there any way to fully escape this script from variable substitution whilst still retaining the single and double quotes required in the powershell script?

2 Answers2

0

Yes, the values are being passed to the file content. You have 3 options:

  1. Add parameters to the .ps1 files and call it with those parameters and the values you want
  2. Use tokens instead of variables and replace those in the target before running the script
  3. Use Get-Variable and Set-Variable

In my opinion, 1 is the best option

Mickey Cohen
  • 997
  • 7
  • 23
  • My issue is with the variables within the powershell script, eg. $retentionDate is being cut out of the final ps1 file – Nick Booth Aug 11 '21 at 09:27
0

I found that the issue was caused by using double quotes for the here-string (@""@) instead of single (@''@);

- task: PowerShell@2
  displayName: "Create IIS Log Cleardown script file"
  env:
    DaysToKeep: ${{ parameters.DaysToKeep }}
  inputs:
    targetType: 'inline'
    script: |
      $DaysToKeep = $env:DaysToKeep
      Set-Content -Path C:\scripts\CleanupScript.ps1 @'
      $logPath = "C:\inetpub\logs\LogFiles"
      $daysKept = $env:DaysToKeep
      $retentionDate = $(Get-Date).AddDays(-$daysKept)
      ...'@

This correctly writes out to the file with the below lines, no longer cutting the powershell variables;

$logPath = "C:\inetpub\logs\LogFiles"
$daysKept = $env:DaysToKeep
$retentionDate = $(Get-Date).AddDays(-$daysKept)