Fredrik
Fredrik

Reputation: 27

powershell string contain only number

I have an array with folder names. I want to loop thru this array and find out if an entry is only 7 in length and only contain numbers.

Can anyone please push me in the correct direction? Thanks!

Upvotes: 2

Views: 28686

Answers (2)

liorlis
liorlis

Reputation: 216

As far as i understood your question :

function Is-Numeric ($Value)
{
    return $Value -match "^[\d\.]+$"
}

$birds = "owl","crow","robin","wren","jay","123"
foreach ($bird in $birds) { if($bird.length -eq 3 -and (Is-Numeric $bird)) {"$bird"} }

just switch it to your case :)

Upvotes: 2

Eduard Uta
Eduard Uta

Reputation: 2607

One solution is while looping through the array names check if the two conditions are met like so:

foreach ($name in "test", "1234567", "test02", "001") {
    if ($name.Length -eq 7 -and $name -match '^\d+$'){
        Write-Host $name
    }
}

Upvotes: 2

Related Questions