组合变量 - PowerShell

Combine Variable - PowerShell

有没有办法将两个字符串组合起来作为当前变量并从中获取数据?我不确定是否有其他方法可以做到这一点。如果有的话,请告诉我。谢谢!

这是我的代码。

$App1 = "Google Chrome"
$App2 = "Mozilla"
$AppExt1 = ".exe"
$AppExt2 = ".msi"
$Apps = @('1','2')
ForEach ($Applications in $Apps) {
    $AppToBeInstalled = '$App' + $_
    $AppExt = '$AppExt' + $_
    Write-Host "Application $AppToBeInstalled to be installed with extension $AppExt"
}

我想要的

Application Google Chrome to be installed with extension .exe
Application Mozilla to be installed with extension .msi

但我只得到空结果。

Application  to be installed with extension 
Application  to be installed with extension 

这是可行的,虽然很不正统,你可以使用 Get-Variable 来获取使用动态名称的变量:

$App1 = "Google Chrome"
$App2 = "Mozilla"
$AppExt1 = ".exe"
$AppExt2 = ".msi"
$Apps = @('1','2')

ForEach ($Applications in $Apps) {
    $AppToBeInstalled = (Get-Variable App$Applications).Value
    $AppExt = (Get-Variable AppExt$Applications).Value
    Write-Host "Application $AppToBeInstalled to be installed with extension $AppExt"
}

> Application Google Chrome to be installed with extension .exe
> Application Mozilla to be installed with extension .msi

更常见的方法可能是使用 hashtable:

$map = @{
    "Google Chrome" = ".exe"
    "Mozilla" = ".msi"
}

ForEach ($key in $map.Keys) {
    $AppToBeInstalled = $key
    $AppExt = $map[$key]
    Write-Host "Application $AppToBeInstalled to be installed with extension $AppExt"
}

> Application Google Chrome to be installed with extension .exe
> Application Mozilla to be installed with extension .msi

是的,你可以,你可以使用

Get-Variable -Name "nameOfVar" -ValueOnly

在你的情况下它看起来像

$App1 = "Google Chrome"
$App2 = "Mozilla"
$AppExt1 = ".exe"
$AppExt2 = ".msi"
$Apps = @('1','2')
ForEach ($Applications in $Apps) {
    $AppToBeInstalled = Get-Variable -Name "App$Applications" -ValueOnly
    $AppExt = Get-Variable -Name "AppExt$Applications" -ValueOnly
    Write-Host "Application $AppToBeInstalled to be installed with extension $AppExt"
}

正如一些人提到的,您可以创建自定义变量,然后在 for 循环中调用它们:

$App1 = [pscustomobject]@{
    Name = "Google Chrome"
    Ext = ".exe"
}
$App2 = [pscustomobject]@{
    Name = "Mozilla"
    Ext = ".msi"
}

$Apps=@($App1,$App2)

ForEach ($App in $Apps) {
    $AppName = $App.Name
    $AppExt = $App.Ext
    Write-Host "Application $AppName to be installed with extension $AppExt"
}

输出将是:

Application Google Chrome to be installed with extension .exe
Application Mozilla to be installed with extension .msi

如果您以后必须继续向脚本添加更多应用程序,可能会更容易。