CodeSpent
CodeSpent

Reputation: 1904

Leading 0 removed from argument in Powershell

New to Powershell, never needed it before I started this job. I'm just making an easier way for me to keep our stores pinging and kill some time learning. Some pretext; Our stores are always 4 numbers, so 1096 is 1096 but 704 is 0704.

Here is my current script:

$args.Length;
foreach ($arg in $args) {
Test-Connection $arg'router' }

Write-Host 'Pinging Store #'$arg

if($arg.legnth -lt 4) {
($arg).insert(0,'0') 
}

If I execute with the argument 1096 all is well in the world, but if I use 0704 the leading 0 disappears. I've tried a number of potential resolutions, but I've found most are trying to remove trailing zeroes so I've just been trying to reverse engineer their solutions. What is the best way to ensure that the leading 0 isn't removed so the host is able to be found.

0704router exists.

704router doesn't exist.

Upvotes: 2

Views: 2052

Answers (2)

greenhorn
greenhorn

Reputation: 11

The [string]$Args[1] worked for me and it seems like the behavior is changing from version to version - same script worked without conversion with PS 2.0

Hope this helps!

Upvotes: 1

briantist
briantist

Reputation: 47792

This looks like an issue of how you call the script. You may be doing something like this:

./MyScript.ps1 1096 0704

Which will give you 2 arguments, but since they are unquoted and contain only digits, they are interpreted as integers, and so you lose leading zeros.

Instead, tell PowerShell you want these as string values by quoting them:

./MyScript.ps1 '1096' '0704'

Upvotes: 2

Related Questions