Author Posts

August 29, 2013 at 7:27 am

What would be the best way to handle this?

If I wanted to insert leading characters based on a length defined by a number. I would like to use in a PowerShell Script where I can do $value.length then subtract that from a predefined number. The difference would then define how many A’s are inserted at the start of the string.

$field = "10"
$value = “FARM”
$value.lengnth returns 4
$field - $value.length is 6.
Create new string of AAAAAAFARM

August 29, 2013 at 7:39 am

$value = $value.PadLeft($field,"A")

August 29, 2013 at 7:41 am

Strings have an Insert() method. Insert(2,"x") would insert "x" at the 2nd position. You could also use the PadLeft() or PadRight() methods, which accept a desired string length and the length you'd like the string padded to. So, if you wanted a string of 10 characters, $string.PadLeft(10,'A') would insert on the left however many A's were needed to make it 10 characters.

August 29, 2013 at 9:14 am

PadLeft() is perfect for what I need. Thank you both.

August 29, 2013 at 1:35 pm

I hadn't used these methods before and was playing around with it. It doesn't appear to work with spaces. Thoughts?

PS C:\Windows\system32> $test = "TEST"

PS C:\Windows\system32> $test.PadLeft(10, "A")
AAAAAATEST

PS C:\Windows\system32> $test = "This is a test"

PS C:\Windows\system32> $test.PadLeft(10, "A")
This is a test

August 29, 2013 at 1:43 pm

I'm not sure what output you're expecting to see, Rob. "This is a test" is longer than 10 characters, so the PadLeft method will just return the original string. If you increased the first argument to something longer than the string, it would start adding "A" characters.

August 29, 2013 at 2:03 pm

Ahhh, I get it now. I was thinking it was going to be 10 A's appended to the front the string versus adding A's for a total length of 10. Though the lightbulb may be dim, it's on now. 🙂 Thanks Dave. Appreciate all your responses, I'm just reading and absorbing want I can.