有沒有辦法組合兩個字串并將其作為當前變數并從中獲取資料?我不確定是否有其他方法可以做到這一點。如果有的話,請告訴我。謝謝你!
這是我的代碼。
$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
uj5u.com熱心網友回復:
這是可行的,雖然很不正統,但您可以使用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
uj5u.com熱心網友回復:
是的,你可以,你可以使用
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"
}
uj5u.com熱心網友回復:
正如有些人提到的,您可以創建自定義變數,然后從 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 使用擴展
名 .msi 安裝應用程式 Mozilla
如果您將來必須繼續向腳本添加更多應用程式,可能會更容易。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/374229.html
