2

My azure piplines yaml script uses powershell to replace a placeholder string in a .CS file with the current date string. This is the line with the value to be replaced (20200101000000)

[assembly: MyCompany.Net.Attributes.BuildDateAttribute("20200101000000")]

This is the powershell step that does it

pwsh: (get-content -path $(versionFile)) | foreach-object {$_ -replace "20200101000000", (get-date -f 'yyyyMMddhhmmss')} | set-content -path $(versionFile)
  displayName: 'Update time stamp file'

I want to alter this step to include the quote characters " around the search string and write them into the new output value along with the new date. But I cannot seem to make that happen.

I mistakenly tried just putting escaped quote characters \" in the search and replace strings. But I guess you cannot escape inside of a single-quoted string so it did not work

pwsh: (get-content -path $(versionFile)) | foreach-object {$_ -replace "\"20200101000000\"", (get-date -f '\"yyyyMMddhhmmss\"')} | set-content -path $(versionFile)

This was the error:

##[command]"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\80625e52-1302-4e35-a799-223ab893bcf1.ps1'"
ParserError: D:\a\_temp\80625e52-1302-4e35-a799-223ab893bcf1.ps1:3
Line |
   3 |  … lyInfo.cs) | foreach-object {$_ -replace "\"20200101000000\"", (get-d …
     |                                                ~~~~~~~~~~~~~~~~~
     | Unexpected token '20200101000000\""' in expression or statement.
##[error]PowerShell exited with code '1'.

I also tried to just using double quotes around the get-date part of the script so I could escape the quote characters but that doesn't seem to work either. I'm guessing that's a limitation of writing script this way.

Is there some other way to achieve what I want?

2 Answers 2

3

The escape character in Powershell is backtick (`), not backslash (\). Try e.g. "`"20200101000000`"".

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the Get-Date -UFormat instead to add arbitrary characters similar to the DateTime.ToString() function in .NET

'[Attrib("20200101000000")]' -replace '"20200101000000"', (get-date -UFormat '"%Y%m%d%H%M%S"')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.