0

I want to output objects based on names from a collection.

The questions has its origin is a script that outputs Active Directory DNS records, parsed by RecordType. But I generalized the code so that testing is easier ... This method would be great for automatic creation of objects by referencing data from object members.

But I don't know how to reference the variable to add the data from the input object. Please see the line with comment "# works not"

Here is an example:

# add example values to create object
Set-Content -Path .\My.csv -Value "Letter;Color;Orientation;Direction"
Add-Content -Path .\My.csv -Value "A;;Top;Left"
Add-Content -Path .\My.csv -Value "A;;Bottom;Right"
Add-Content -Path .\My.csv -Value "B;Green;;Left"
Add-Content -Path .\My.csv -Value "B;Red;;Left"
Add-Content -Path .\My.csv -Value "C;Black;Mid;"
Add-Content -Path .\My.csv -Value "C;Red;Top;"

# define members
$m_A = @("Letter", "Orientation", "Direction")
$m_B = @("Letter", "Color", "Direction")
$m_C = @("Letter", "Color", @{n="Richtung";e={"Orientation"}})

# define output collections
$c_A = @()
$c_B = @()
$c_C = @()

# fill output collections
$in = Import-csv -Path .\My.csv -Delimiter ";" 
$in | ForEach-Object{
  $c_A += $_ | Select-Object (Get-Variable -Name $("m_" + $_.Letter)).Value # Works
  $c_$_.Letter += $_ | Select-Object (Get-Variable -Name $("m_" + $_.Letter)).Value # Works not
}

@("A", "B", "C") | ForEach-Object{
    (Get-Variable -Name $("c_" + $_)).Value | Export-Csv -Path .\$_ -Delimiter ";" -Encoding UTF8
}
  • can you provide sample data? – another victim of the mouse May 02 '22 at 17:47
  • What you're looking for is _variable indirection_, where you refer to a variable _indirectly_, via its name stored in a different variable or provided by an expression. PowerShell enables this via the [`Get-Variable`](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/get-variable) and [`Set-Variable`](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/set-variable) cmdlets (you're already using `Get-Variable`), but note that there are usually better alternatives. See [the linked duplicate](https://stackoverflow.com/q/68213804/45375) for details. – mklement0 May 02 '22 at 19:27
  • Thanks for explaining variable indirection. Yes, this ist the solution. I am missing `Get-Variable -passthru`, would bei cool. – StormDeep May 03 '22 at 20:30
  • _@another victim of the mouse_ You mean the origin DNS approach? – StormDeep May 03 '22 at 20:35

0 Answers0