4c74356b41
4c74356b41

Reputation: 72171

Get string length that is created dynamically

Lets say I want to do something like this:

$string = 'arbitrary string' # << is random
(Do-Something -Name ($string + (Get-Random)).Substring(0, [math]::Min(20, ??)

How do I refer to current length of the result of the expression inside ($string + (Get-Random))?

Fails when using Substring(0, 20) when string shorter than 20 chars

Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: length"

Upvotes: 2

Views: 660

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174660

You'll have to assign the new string to a variable:

Do-Something -Name ($s = $string + (Get-Random)).Substring(0, [math]::Min(20,$s.Length))

A less terse version of the above:

$Name = $string + (Get-Random)
if($Name.Length -gt 20){
    $Name = $Name.Substring(0, 20)
}
Do-Something -Name $Name

As mentioned in the comments, you could also select the first 20 chars by index from the string and combine again with the -join operator (v3.0 and newer):

$Name = "$string$(Get-Random)"[0..19] -join ''

Feeling frisky? Use regex (as suggested by wOxxOm):

$Name = "$string$(Get-Random)" -replace '^(.{20}).+','$1'

If the concatenated string is less than 20 characters nothing will be replaced, otherwise the entire string will match and get replaced by the first 20 characters

Another approach would be to generate a random number of X digits where X is 20 - $string.Length (only works if $string is guaranteed to be between 2 and 19 characters long):

$Name = "$string$(Get-Random -Min ('1' * (20 - $string.Length)) -Max ('9' * (20 - $string.Length)))"

Upvotes: 4

Related Questions