Define Powershell variable to have a value of a list

做~自己de王妃 提交于 2021-02-05 08:42:17

问题


I have some variables as below:

$a = "string1"
$b = "string2"
$c = "string3"

Now i want to define a variable $list to with all of the content from $a,$b,$c to look like this:

$list = "
a: string1
b: string2
c: string3
"

how can i do that?

*** Edit: the content of the list must be EXACT like i wrote, that means, the part like "a: " b: ", ... must be the same too


回答1:


Looks like you don't want an actual list, but a string with a listing of variables. A multiline string with the names and values of your variables could be defined like this:

$list = @"
a: ${a}
b: ${b}
c: ${c}
"@

Another, more dynamic, option would be something like this:

$list = 'a', 'b', 'c' | ForEach-Object {
    "${_}: $(Get-Variable $_ -ValueOnly)"
} | Out-String

where you specify a list with the variable names, output strings containing each variable name and the corresponding value, and merge those into a single string at the end.




回答2:


Powershell has 'arrays':

"An array is a data structure that is designed to store a collection of items. The items can be the same type or different types."

In your case, if you have variables already, you can include them in an array:

$myarray = $a, $b, $c
Write-Host $myarray

or

$myarray = @($a, $b, $c)
Write-Host $myarray

or you can create an associative array for enter your key-value elements:

$otherarray = @{}            # create en empty array
$otherarray['a'] = 'string1' # add key-value pairs
$otherarray['b'] = 'string2'
$otherarray['c'] = 'string3'
Write-Host $otherarray.c     #print in console example

Edit: by your example I recommended arrays because I think it's a simple use case, but if you will modify it frecuently, better use System.Collection.ArrayList:

$mylist = New-Object System.Collections.ArrayList
$mylist.add($a)
$mylist.add($b)
$mylist.add($c)
$Write-Host $mylist



回答3:


[string[]]$list = "string1","string2","string3"

Edit:

I did not read your question fully, here's an example of a hash table with key=value pairs:

$a = "string1"
$b = "string2"
$c = "string3"

$list = @{
a = $a
b = $b
c = $c
}

Ultimately it depends on whether you know how to use the construct, and what you're using it for. There are many ways to achieve a simple list/array/table of 3 strings.




回答4:



You can make use of New-Object System.Collections.ArrayList to create a list and use it. eg:

$a = "string1"
$b = "string2"
$c = "string3"

$list = New-Object System.Collections.ArrayList
$list.Add($a)
$list.Add($b)
$list.Add($c)

Now $list[1] gives string2.

Hope this helps. :)




回答5:


I suspect other answers have given you what you're after already. However, here are other solutions for different interpretations of your question...


If you wish to have the list populated with the values which are in a, b, and c at run time, you can do this:

$a = "string1"
$b = "string2"
$c = "string3"

$list = @('a','b','c') | Get-Variable | ForEach-Object{'{0}: {1}' -f $_.Name, $_.Value}
$list

i.e. this finds the variables a, b, and c and populates list with strings based on the variable's name and value formatted as name: value.


Alternatively, if you wish to populate a list with a single "here-string" (i.e. a string which may be multi-line) split to be one item per line, you could do this:

$list = @'
a: string1
b: string2
c: string3
'@ -split '[\r\n]+'
$list.Count #prove that our list contains 3 items rather than 1 multi line item
$list # show the contents of the array

This takes the multi-line string and splits it on line breaks (using a regex to ensure it treats different potential line endings the same way, and skips over multiple sequential line breaks to avoid creating blank entries between items).


Finally, if you wanted to populate variables a, b, and c from the list, you could use something like this:

$list = @(
    'a: string1',
    'b: string2',
    'c: string3'
)

$list | ForEach-Object {
    if ($_ -match '^\s*(?<VarName>[^\:]+)\s*:\s*(?<VarValue>.*)$') {
        Write-Verbose ('Name: {0}; Value {1}' -f $Matches.VarName, $Matches.VarValue)
        New-Variable -Name $Matches.VarName -Value $Matches.VarValue -Force
    }
}
$a
$b
$c



回答6:


I think a hashtable is what you are looking for:

$list = @{}
$list.a = 'string1'
$list.b = 'string2'
$list.c = 'string3'

foreach( $item in $list ) {
  # do something
}

# get content of hash:

$var = $list['a']

# or

$var = $list.a


来源:https://stackoverflow.com/questions/50443564/define-powershell-variable-to-have-a-value-of-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!