I am trying to create a PowerShell script that adds two leading zeros to all the numbers in a particular column.This script is able to add the two zeros to the column values, but only at the end of the values.
I have tried converting the data type of $zeros and $employeeNumber but have been unable to get the script to add leading zeros to the column values. Any guidance is greatly appreciated!
CodePudding user response:
That's because numbers don't have leading zeros. If you want to pad zeros to the left of the number you have to treat it like a string.
$employeeNumber = 73128
$employeeNumberString = $employeeNumber.ToString()
$paddedEmployeeNumberString = $employeeNumberString.PadLeft(7,'0')
That will leave $paddedEmployeeNumberString
with a value of 0073128
.
CodePudding user response:
Looking at the images you posted, this is not just about padding numbers with leading zeroes, but mainly that these leading zeroes 'dissapear' when the csv file is opened in Excel.
If you want to have Excel respect those zeroes, write them out in your CSV file prefixed with a TAB character:
"`t{0:D7}" -f 73128
produces 0073128
If you need more total digits, just change {0:D7}
into {0:D9}
or {0:D25}
or..