变量附加打印文字字符串

变量附加打印文字字符串

我有一个变量$emp,并且在这个变量中为每个员工设置了一个单独的文件夹变量。所以我有 1)$GeorgeFullSaveDir和 2) $JamesFullSaveDirforeach我使用循环迭代的值,$emp以便减少/重复使用代码,是否可以不为每个员工 savedir 创建单独的变量,并将的值附加$emp到 FullSaveDir?我尝试了以下方法,但没有成功

$employees = @('George', 'James')
foreach ($emp in $employees)
{
    $SaveDirRoot = "R:\Employees\"
    $GeorgeSaveDir = "George\"
    $JamesSaveDir = "James\"
    $GeorgeFullSaveDir = $SaveDirRoot+$GeorgeSaveDir
    $JamesFullSaveDir = $SaveDirRoot+$JamesSaveDir

    Write-Host $emp+FullSaveDir
    #Desired output will be
    #R:\Employees\George\ 
    #R:\Employees\James\
}

进一步解释 - 对于变量的每次迭代,$emp我希望能够附加$emp+FullSaveDir并生成该特定员工的结果。因此,使用当前语法,它将生成

1)R:\员工\乔治\
2)R:\员工\詹姆斯\

答案1

您可以使用Get-Variablecmdlet 通过名称引用变量:

$employees = 'George', 'James'
$SaveDirRoot = "R:\Employees\"
$GeorgeSaveDir = "George\"
$JamesSaveDir = "James\"
$GeorgeFullSaveDir = $SaveDirRoot+$GeorgeSaveDir
$JamesFullSaveDir = $SaveDirRoot+$JamesSaveDir

foreach ($emp in $employees)
{
    Write-Host (Get-Variable ($emp+'FullSaveDir') -ValueOnly)
}

但是,恕我直言,您不应该为每个员工使用多个变量,而应该将所有与员工相关的信息存储在一个对象中:

$employees = @(
    @{
        Name = 'George'
        SaveDir = "George\"
    }
    @{
        Name = 'James'
        SaveDir = "James\"
    }
)
$SaveDirRoot = "R:\Employees\"

foreach ($emp in $employees)
{
    $emp.FullSaveDir = $SaveDirRoot+$emp.SaveDir
}

foreach ($emp in $employees)
{
    Write-Host $emp.FullSaveDir
}

相关内容