Prime Prime - 3 months ago 15
PowerShell Question

append forloop iterator variable value

Am calling for loop and trying to append the $i value along with a variable called inside the function. not sure how to do this. Everytime I get a error saying "Unexpected token 'i' in expression or statement." any suggestions/idea please.

Thanks to Chris. His code works perfectly..

code :

function Get-Data {
param(
# Consider giving this a more meaningful name
[Int]$i
)

# Assigns the value in the first index from -split to $null
# and the value in the second index to $msgs.
$null, $msgs = (b2b.exe -readparams "msgs${i}data" | Select-Object -Skip 1 -First 1) -split '='
$null, $bytes = (b2b.exe -readparams "bytes${i}data" | Select-Object -Skip 1 -First 1) -split '='

[PSCustomObject]@{
MData = $msgs.Trim()
BData = $bytes.Trim()
}
}

for ($i=0; $i-le 3; $i++) {
$data = Get-Data $i
write-host "for MData$i $($data.MData)"
write-host "for BData$i $($data.BData)"
}

Answer

I can't tell you if this will work, but I would not rely on globally assigned variables to pass information out of a function.

I suspect it may need a bit of work around construction of the parameters for b2b.exe.

function Get-Data {
    param(
        # Consider giving this a more meaningful name
        [Int]$i
    )

    # Assigns the value in the first index from -split to $null
    # and the value in the second index to $msgs.
    $null, $msgs = (b2b.exe -readparams "msgs${i}data" | Select-Object -Skip 1 -First 1) -split '='
    $null, $bytes = (b2b.exe -readparams "bytes${i}data" | Select-Object -Skip 1 -First 1) -split '='

    [PSCustomObject]@{
        MData = $msgs.Trim()
        BData = $bytes.Trim()
    }
}

for ($i=0; $i-le 3; $i++) {
    $data = Get-Data $i
    write-host "for MData$i $($data.MData)"
    write-host "for BData$i $($data.BData)"
}
Comments