在 PowerShell 中从 2 个变量创建一个递增变量 [英] Create an incrementing variable from 2 variables in PowerShell

查看:36
本文介绍了在 PowerShell 中从 2 个变量创建一个递增变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,首先我认为自己是一个新手,有很多关于 PowerShell 的知识,这是我有史以来的第一篇文章.我正在尝试遍历一些数据并将其放入自定义对象并将它们放入单独的数组中以供以后使用.问题是我想通过使用计数器 $i 创建一个表示 $week_data1 的变量,这样我就可以减少所需的代码量.我确实有一个串联变量被写出: write-host '$week++ ='$week$i 但我认为它被表示为一个字符串?如何让 $week_data$i 代表数组插入数据?

输入数据.每个星期都在星期六结束.$week1=@('2021-05-01')$week2=@('2021-05-02', '2021-05-03', '2021-05-04', '2021-05-05', '2021-05-06', '2021-05-07', '2021-05-08')$week3=@('2021-05-09', '2021-05-10', '2021-05-11', '2021-05-12', '2021-05-13', '2021-05-14', '2021-05-15')$week4=@('2021-05-16', '2021-05-17', '2021-05-18', '2021-05-19', '2021-05-20', '2021-05-21', '2021-05-22')$week5=@('2021-05-23', '2021-05-24', '2021-05-25', '2021-05-26', '2021-05-27', '2021-05-28', '2021-05-29')$week6=@('2021-05-30', '2021-05-31')$month =@($week1, $week2, $week3, $week4, $week5, $week6)创建要填充的输出结构.$week_data1=@()$week_data2=@()$week_data3=@()$week_data4=@()$week_data5=@()$week_data6=@()$month_data =@($week_data1, $week_data2, $week_data3, $week_data4, $week_data5, $week_data6)循环遍历数组并计算正在处理的周数.$i = 0foreach($week in $month){ $i++$n=0在这里,我可以写出一个变量并正确连接.**写主机'$week++ ='$week$i**foreach($day in $week){$n++写主机 '$day ='$day从 .csv 文件中提取数据以填充自定义对象.foreach($csv 中的 $line){if($line -match $day)匹配 CSV 文件中包含正确日期的行.一个月中的每个日期在文件中添加一行.{ #write-host '$line.Day = ' $line.Day# 自定义对象稍后使用$date_data = [PSCustomObject] @{week_numb = $i日期 = $line.Day尝试 = $line.Attempts连接 = $line.Connects}我尝试了不同的语法版本,但在这里不起作用?我想将自定义对象数据放入正在处理的一周的新数组中.#write-host '$week_data[$i]='$week_data[$i]$week_data$i += $date_data # 将 csv 文件中的数据添加到#$week_data[$i] += $date_data}}}}

使用 $week_data$i 作为变量时出现错误:

在第 38 行字符:17

  •  $week_data$i += $date_data # 将 csv 文件中的数据添加到

  •  ~~

表达式或语句中出现意外标记$i".+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException+ FullQualifiedErrorId : UnexpectedToken

解决方案

您正在寻找变量间接,即通过存储在另一个变量中的名称或从表达式返回的名称间接引用变量的能力.>

但是请注意,通常有更好的替代方案,例如使用数组或 hashtables 作为多值容器.

如果您确实需要使用变量间接寻址,请使用 Get-VariableSet-Variable:

$week_data1 = 'foo', 'bar'$i = 1# 同:$week_data1# 注意$"不得指定为名称的一部分.获取变量week_data$i"-仅值# 同: $week_data1 = 'baz', 'quux'设置变量week_data$i"巴兹, quux# 更新现有值需要嵌套两个调用:# 同: $week_data1 += 'quuz'设置变量week_data$i"((Get-Variable "week_data$i" -ValueOnly) + 'quuz')

顺便说一句:扩展"带有 += 的数组很方便,但效率低下:每次都必须在幕后创建一个 数组 - 请参阅 这个答案.

同样,与直接赋值和变量引用相比,调用 cmdlets 来设置和获取变量的性能很差.


至于你尝试了什么:

  • $week_data$i = ... 是一个赋值表达式,它被解释为直接并置两个变量,$week_data$i,这会导致您看到的语法错误.

  • 相比之下,Write-Output $week_data$i 是一个命令,而 $week_data$i 是也被解释为两个变量引用,作为一个命令参数它在语法上是有效的,并且会简单地传递两个变量的(字符串化)连接价值观;换句话说: $week_data$i 就像是双引号一样,即 可扩展字符串,因此该命令等效于 Write-Output "$week_data$i"

OK, First I consider myself a newbie and have much to learn about PowerShell and this is my first post ever. I am trying to loop through some data and put it into a custom object and put them into separate arrays for later use. The issue is that I want to create a variable representing $week_data1 by using a counter $i so I can reduce the amount of code required. I do have a concatenated variable being written out: write-host '$week++ ='$week$i But I think it is being represented as a string? How can I get $week_data$i to represent the array to insert the data?

Input data. Each week ends on Saturday.
    $week1=@('2021-05-01')
    $week2=@('2021-05-02', '2021-05-03', '2021-05-04', '2021-05-05', '2021-05-06', '2021-05-07', '2021-05-08')
    $week3=@('2021-05-09', '2021-05-10', '2021-05-11', '2021-05-12', '2021-05-13', '2021-05-14', '2021-05-15')
    $week4=@('2021-05-16', '2021-05-17', '2021-05-18', '2021-05-19', '2021-05-20', '2021-05-21', '2021-05-22')
    $week5=@('2021-05-23', '2021-05-24', '2021-05-25', '2021-05-26', '2021-05-27', '2021-05-28', '2021-05-29')
    $week6=@('2021-05-30', '2021-05-31')
    $month =@($week1, $week2, $week3, $week4, $week5, $week6) 
    
Create the output structures to be populated.
    $week_data1=@()
    $week_data2=@()
    $week_data3=@()
    $week_data4=@()
    $week_data5=@()
    $week_data6=@()
    $month_data =@($week_data1, $week_data2, $week_data3, $week_data4, $week_data5, $week_data6)
Loop through the array and count the week number that is being processed.

    $i = 0
    foreach($week in $month)
    { $i++
    $n=0

Here I can write out a Variable and it concatenates properly.
    **write-host '$week++ ='$week$i**
        foreach($day in $week)
        {$n++
        write-host '$day ='$day
Pull in data from a .csv file to populate the custom object.
        foreach($line in $csv) 
         {
          if($line -match $day)
Match the line in the CSV file that has the correct Date in it. One line in the file per date in the month.
          { #write-host '$line.Day = ' $line.Day
            # custom object to be used later 
            $date_data = [PSCustomObject] @{
             week_numb = $i
             date = $line.Day
             attempts = $line.Attempts
             connects = $line.Connects
            }
I have tried different syntax versions but it does not work here? I want to put the custom object data into the new array for the week being processed. 
          #write-host '$week_data[$i]='$week_data[$i]
          $week_data$i += $date_data # Add data from csv file into a 
          #$week_data[$i] += $date_data
          }
         }
    
        }
    }

Issue using $week_data$i as a variable I get an error:

At line:38 char:17

  •   $week_data$i += $date_data # Add data from csv file into a
    

  •             ~~
    

Unexpected token '$i' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken

解决方案

You're looking for variable indirection, i.e. the ability to refer to a variable indirectly, by a name stored in another variable or returned from an expression.

Note, however, that there are usually superior alternatives, such as using arrays or hashtables as multi-value containers.

If you do need to use variable indirection, use Get-Variable and Set-Variable:

$week_data1 = 'foo', 'bar'

$i = 1

# Same as: $week_data1
# Note that "$" must NOT be specified as part of the name.
Get-Variable "week_data$i" -ValueOnly

# Same as: $week_data1 = 'baz', 'quux'
Set-Variable "week_data$i" baz, quux

# Updating an existing value requires nesting the two calls:
# Same as: $week_data1 += 'quuz'
Set-Variable "week_data$i" ((Get-Variable "week_data$i" -ValueOnly) + 'quuz')

As an aside: "extending" an array with += is convenient, but inefficient: a new array must be created behind the scenes every time - see this answer.

Similarly, calling cmdlets to set and get variables performs poorly compared to direct assignments and variable references.


As for what you tried:

  • $week_data$i = ... is an assignment expression, which is interpreted as directly juxtaposing two variables, $week_data and $i, which causes the syntax error you saw.

  • By contrast, something like Write-Output $week_data$i is a command, and while $week_data$i is also interpreted as two variable references, as a command argument it is syntactically valid, and would simply pass the (stringified) concatenation of the two variable values; in other words: $week_data$i acts as if it were double-quoted, i.e. an expandable string, and the command is therefore equivalent to Write-Output "$week_data$i"

这篇关于在 PowerShell 中从 2 个变量创建一个递增变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆