powershell - 动态变量属性

标签 powershell

我正在foreach循环中生成一个名称是动态的变量,我需要设置属性

$variableName = "res" + $i
New-Variable -Name $variableName -Value New-Object System.Windows.Forms.Label

然后我需要添加属性,但只需使用
$variableName.text = "ipsum"  

将设置$ variableName的属性,而不是设置的变量。

最佳答案

您应该能够使用Get-Variable cmdlet通过-ValueOnly参数执行此操作,以便获得返回的变量,而不是包含有关该变量的属性的对象:

(Get-Variable $variableName -ValueOnly).text = "ipsum"

请注意,您的代码中还有一个错误,即:
New-Variable -Name $variableName -Value New-Object System.Windows.Forms.Label

需要是:
New-Variable -Name $variableName -Value (New-Object System.Windows.Forms.Label)

屏幕截图:

Accessing a dynamically named variable with PowerShell

关于powershell - 动态变量属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43096836/

相关文章:

Azure PowerShell::如何打印属性列表

powershell - 有没有更好的方法使用 Powershell 将标题添加到 CSV 文件?

windows - 通过 PowerShell 更改 Word 文件的背景颜色

powershell - 函数管道如何跳过进程 block ?类似于 foreach 循环中的 continue

powershell - 如何在 powershell 脚本中使用 Get-clipboard 输出?

powershell - 找出文件是否是 PowerShell 中的符号链接(symbolic link)

powershell - 打开Word应用程序时的“Document is used”

powershell - 无法将 'System.Object[]'转换为 'System.DateTime'

windows - 为什么通过管道传递我的命令 | % {echo "$_"} 让 UTF-8 工作?

powershell - 位置参数问题