组合变量 - PowerShell

Posted

技术标签:

【中文标题】组合变量 - PowerShell【英文标题】:Combine Variable - PowerShell 【发布时间】:2022-01-10 05:39:20 【问题描述】:

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

这是我的代码。

$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 

【问题讨论】:

【参考方案1】:

正如一些人提到的,您可以创建自定义变量,然后在 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"

输出将是:

使用扩展名 .exe 安装应用程序 Google Chrome 应用程序 Mozilla 以扩展名 .msi 安装

如果您将来必须继续向脚本添加更多应用,可能会更容易。

【讨论】:

这很好而且更容易理解。非常感谢! 没问题,很乐意提供帮助。【参考方案2】:

这是可行的,虽然很不正统,您可以使用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

【讨论】:

@Mr.Rak 很乐意为您提供帮助。请注意,如果您要使用Get-Variable 方法而不是hashtable,请考虑使用-ValueOnly 开关而不是(Get-Var...).Value,正如Vojin Purić 在他的回答中指出的那样。 明白。谢谢!【参考方案3】:

是的,你可以使用

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"

【讨论】:

这也有效。非常感谢!

以上是关于组合变量 - PowerShell的主要内容,如果未能解决你的问题,请参考以下文章

组合变量 - PowerShell

GraphQL 变量组合验证

Python使用matplotlib可视化多分类变量组合下分组小提琴图使用seaborn中的catplot函数可视化多分类变量组合下分组小提琴图(Categorical Plots)

您如何使用 Scikit learn 预测分类变量和连续变量的组合?

Smarty:在修饰符中组合两个变量

shell 组合新的变量名