2016-08-18 67 views
0

我正在調用循環並試圖追加$ i值以及函數內部調用的變量。不知道如何做到這一點。每當我在表達或聲明中發現「意外的令牌」時,我都會收到一個錯誤消息。「任何建議/想法請。append forloop迭代器變量值

感謝克里斯。他的代碼工作完美..

代碼:

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

當你使用'$ M $ i'時,你試圖對變量做什麼?連接成一個字符串?如果是這樣,你需要使它成爲一個字符串'「$ M $ i」'。如果你想創建一個基於$ i的變量,你需要使用'New-Variable'M $ i「'。 –

+0

通過添加一個您試圖用遞歸函數解析的示例,您可能會更好。我沒有任何問題通過$ i來控制深度,但是你的變量賦值在沒有上下文的情況下會令人困惑。 –

+0

@Chris,我試圖創建一個基於$ i的變量,所以猜測,我需要嘗試你的建議,即新變量「M $ i」..讓我試試 – HULK

回答

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