pmdci
pmdci

Reputation: 300

PowerShell: Triming and adding trailing zeroes

I have a string which can be from about 5 characters to any given size. What I would like to do is get the first 10 characters, then add 5 trailing zeroes and save the result at another variable. However I need the end string to have 15 characters. So if there are only 9 characters, there should be 6 trailing zeroes. If there are only 8 characters, then 7 trailing zeroes, etc.

JOE.BLOGS -> JOE.BLOGS000000

ANDREW.SMITH -> ANDREW.SMI00000

JIM -> JIM000000000000

I am having a particular hard time since the SubString gives me an error if the string is shorter than what I specify:

$shadowSAM = $shadowUPN.substring(0,10) + '00000'

Plus I am not sure on how to add the correct number of trailing zeroes depending on how long the string actually is (an if/then/else of switch statement would be a cringe-fest).

Is this possible in PowerShell?

Upvotes: 1

Views: 908

Answers (2)

Esperento57
Esperento57

Reputation: 17472

oter solution with "0"*15 to replace padleft

 (($str2 -replace '(.{10}).+','$1') + ("0" * 15)).Substring(0, 15)

Upvotes: 1

Esperento57
Esperento57

Reputation: 17472

try this

(($str -split '' | select -first 10)  -join '').PadRight(15, "0")

or this

($str[0..9] -join '').PadRight(15, "0")

or this

$str.substring(0, [Math]::Min($str.Length, 10)).PadRight(15, "0")

or this

($str -replace '(.{10}).+','$1').PadRight(15, "0") 

Upvotes: 1

Related Questions