Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

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:

I have a System.Array with two values:

$Years = 2015, 2016

Another variable $Transactions has a list of various transactions.

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"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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 "*.$_"
}

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

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 '.*.') }

(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...