追加forloop迭代器变量值

时间:2016-08-18 10:09:28

标签: powershell powershell-v2.0

调用循环并尝试将$ i值与函数内部调用的变量一起追加。不知道该怎么做。每当我在表达式或语句中出现“意外令牌'我'时,都会收到错误消息。”任何建议/想法请。

感谢克里斯。他的代码很完美......

代码:

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)"
}

1 个答案:

答案 0 :(得分:1)

我无法告诉你这是否有效,但我不会依赖全局指定的变量来传递函数中的信息。

我怀疑在构建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)"
}