PowerShell:如何间接引用变量

PowerShell : how do I indirectly reference a variable

在 Powershell 中,如何间接引用变量?

我有 table 代码的许多部分都引用了它,所以我有一个 table 名称列表,如下所示:

$xTableName = "Tbl_x"
$yTableName = "Tbl_y"
$zTableName = "Tbl_z"

我有一个函数,我想向其传递一个表示 table:

的字符串
function getResult($entityName)
{
$tableName="$" + $entityName + "TableName"
$sqlCommand = "SELECT * FROM " + ${$tableName}
run query etc...
}

我打电话

getResult("x")

我正在尝试获取 $sqlCommand = "SELECT * FROM Tbl_x" 但获取的是 "SELECT * FROM $xTableName"

我该如何实现?

您可以使用 Get-Variable -ValueOnly 按名称获取变量的值:

$tableName = Get-Variable "${entityName}TableName" -ValueOnly

也就是说,更快且不易出错的方法是利用字典将实体名称映射到 table 名称:

function getResult($entityName)
{
    $tableMapping = @{
        x = "Tbl_x"
        y = "Tbl_y"
        z = "Tbl_z"
    }
    if(-not $tableMapping.ContainsKey($entityName)){
        Write-Error "Invalid entity name '$entityName'"
    }
    else {
        $tableName = $tableMapping[$entityName]
        $sqlCommand = "SELECT * FROM ${$tableName}"
        # execute sql query ...
    }
}

更简洁的方法是使用正则表达式。我们可以这样做:

$xTableName = "Tbl_x"
$yTableName = "Tbl_y"
$zTableName = "Tbl_z"

function getResult($TableName)
{
    $sqlCommand = "SELECT * FROM tableName" -creplace "tableName","$TableName"
}
getResult($xTableName)