Note: This answer focuses on improving on the split-into-tokens-by--
approach from Richard's helpful answer, though note that that approach isn't fully robust, because git
tag names may themselves contain -
characters, so you cannot blindly assume that the first -
instance ends the tag name.
To account for that, use Richard's robust solution instead.
Just to offer a more PowerShell-idiomatic variant:
# Stores '0.3.1' in $tag, and 'g3b885c5' in $commitId
$tag, $commitId = ('0.3.1-15-g3b885c5' -split '-')[0, -1]
PowerShell's -split
operator is used to split the input string into an array of tokens by separator -
While the [string]
type's .Split()
method would be sufficient here, -split
offers many advantages in general.
[0, -1]
extracts the first (0
) and last (-1
) element from the array returned by -split
and returns them as a 2-element array.
$tag, $commitId =
is a destructuring multi-assignment that assigns the elements of the resulting 2-element array to a variable each.