在 PowerShell 中调用动态变量 [英] Calling dynamic variable in 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
到 Where-Object
而不是使用 $Transactions | 的值其中 ...
作为变量的值.你需要括号才能工作:
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屋!