在PowerShell中调用动态变量 [英] Calling dynamic variable in PowerShell

查看:400
本文介绍了在PowerShell中调用动态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个新的变量,该变量将使用具有动态名称的其他变量作为其值.这是我想要做的:

I am trying to create a new variable that would use other variable with dynamic name as its value. Here's what I am trying to do:

我有一个带有两个值的System.Array:

I have a System.Array with two values:

$Years = 2015, 2016

另一个变量$ Transactions具有各种交易的列表.

Another variable $Transactions has a list of various transactions.

我正尝试通过以下方式使用每个$ Years值:

I am trying to use each of those $Years values in the following way:

ForEach($Year in $Years){

New-Variable -Name "Transactions_$Year" -Value $Transactions | Where {$_.Date -like "*.$Year"

现在(在同一ForEach循环内)我想做的就是在创建另一个新变量时使用该$ Transactions_ $ Year值,如下所示:

Now what I would like to do (within that same ForEach-loop) is to use that $Transactions_$Year value when I am creating a another new variable, like this:

New-Variable -Name "Income_$Year" -Value $Transactions_$Year |  Where {$_.Amount -NotLike "-*"} | Measure-Object Amount -Sum | Select -ExpandProperty Sum

}

这有可能吗,或者您有其他方法可以实现这一目标吗?

Is this possible, or do you have any alternative ways how I could achieve this?

推荐答案

首先,您的New-Variable调用没有执行您认为的操作,因为您将New-Variable的输出通过管道传输到,而不是将$Transactions | Where ...的值用作变量的值.您需要括号才能使其正常工作:

First of all, your New-Variable invocation doesn't do what you think it does, as you'd pipe the output of New-Variable to Where-Object instead of using the value of $Transactions | Where ... as value for the variable. You need parentheses for that to work:

New-Variable -Name "Transactions_$Year" -Value ($Transactions | Where {$_.Date -like "*.$Year" })

如果绝对必须使用此方法,则可以通过Get-Variable重新获得变量:

If you absolutely have to use this approach, then you can get the variables again via Get-Variable:

Get-Variable Transactions_$Year | % Value

但是,具有魔术名称的多个变量是解决此问题的一种较差的方法.您可能宁愿要一张地图:

However, multiple variables with magic names is a rather poor way of solving this. You probably rather want a map:

$TransactionsPerYear = @{}
$Years | ForEach-Object {
  $TransactionsPerYear[$_] = $Transactions | Where Date -like "*.$_"
}

您可以使用$TransactionsPerYear[2015]获取2015年的所有交易.

And you can get all transactions for 2015 with $TransactionsPerYear[2015].

另一种方法是Group-Object,它甚至不需要一开始就列出可能的年份,而是通过一些属性或表达式结果将多个对象分组:

Another way is Group-Object which doesn't even require a list of possible years to begin with, but groups a number of objects by some property or expression result:

$TransactionsPerYear = $Transactions | Group-Object { [int]($_.Date -replace '.*\.') }

(这是对它如何工作的猜测.您的日期字符串似乎包含一个不超过一个句点的字符,此后没有年份,则没有年份,因此可能类似于dd.MM.yyyy日期格式.

(This is a guess on how it could work. It seems like your date string contains something up to a period, after which there is the year and nothing else, so perhaps something like dd.MM.yyyy date format.

这篇关于在PowerShell中调用动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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