0

My powershell command below

$BUILD_SOURCEVERSIONMESSAGE= (Get-Item Env:\BUILD_SOURCEVERSIONMESSAGE) 

returns output in this format

2018-10-26T01:08:44.7409834Z BUILD_SOURCEVERSIONMESSAGE     Merge 569594f057e2c4bd0320159855e81e14216ca66f into 41107d0f0db5ef2986831db2182280e0c...

I am trying to parse the string 569594f057e2c4bd0320159855e81e14216ca66f from the output above.

I tried converting the output to a string, splitting it on whitespace, and accessing the second element of the array as follows. However, I get empty string. How can I access the required string?

echo $BUILD_SOURCEVERSIONMESSAGE
$out = $BUILD_SOURCEVERSIONMESSAGE | Out-String
$out1 = $out.split()
echo $out1[1]
0

1 Answer 1

2

The concise equivalent of command Get-Item Env:\BUILD_SOURCEVERSIONMESSAGE - i.e., retrieving the value of environment variable BUILD_SOURCEVERSIONMESSAGE - is the expression $env:BUILD_SOURCEVERSIONMESSAGE.

Using the unary form of Powershell's -split operator, which splits the input by any nonempty run of whitespace (while stripping leading and trailing whitespace), you can get the desired output as follows:

PS> (-split $env:BUILD_SOURCEVERSIONMESSAGE)[3]
569594f057e2c4bd0320159855e81e14216ca66f

Index 3 extracts the 4th token resulting from the tokenization via -split.


If you want to use string interpolation with the result:

$prefix = 'before<'; $postfix = '>after'
$val = (-split $env:BUILD_SOURCEVERSIONMESSAGE)[3]

# Output a synthesized string that applies a pre- and postfix, using
# {...} to enclose variable names to avoid ambiguity.
"${prefix}${val}${postfix}"

The above yields:

before<569594f057e2c4bd0320159855e81e14216ca66f>after
Sign up to request clarification or add additional context in comments.

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.