MAX GRIMM
MAX GRIMM

Reputation: 109

Validate the input variable and action further

I am new to powershell

In my script, have a input variable called $inputVar this can be a number like 2,3,4 but will be single integer or this can be comma separated value like 2,3,4,5.

want if it is a integer then do nothing, but if it a comma separated variable then print each element inside the comma separated,

for example:

 if  ($inputVar is an integer) {
}
else {
   foreach ($var in $inputVar){
    Write-Host $var
}
}

Upvotes: 1

Views: 147

Answers (1)

Theo
Theo

Reputation: 61178

It depends if $inputvar is a string like "1" or "1,2,3" or an integer value like 1 or an array of integers like 1,2,3..

When it's a string you could split the $inputvar on possible commas, force that into an array even if there is only one value in it by surrounding it with @() and then use the .Count property like:

$inputvar = "1,2,3"
if (@($inputvar -split ',').Count -gt 1) { Write-Host ($inputvar -replace ',', [environment]::NewLine) }

When it is not a string, but an array of integers or a single integer value, you could do:

$inputvar = 1,2,3
# (`!` is the same as `-not`)
if (![int]::TryParse($inputvar, [ref]$null)) { $inputvar | ForEach-Object { Write-Host $_ }}

or

if ($inputvar -is [array]) { $inputvar | ForEach-Object { Write-Host $_ }}

Upvotes: 1

Related Questions