简体   繁体   English

如何使用参数名称运行powershell命令是可变的

[英]How to run powershell command with parameter name is variable

I need to run the same command Get-QadUser and Set-QadUser to one property and his value but my property is a variable. 我需要将相同的命令Get-QadUserSet-QadUser到一个属性和他的值,但我的属性是一个变量。

my code (Set doesn't work !) : 我的代码(设置不起作用!):

$property = 'MobilePhone' # OK
$value = ($User | get-QadUser -IncludedProperties $property).$property # OK
$user | Set-QadUser -$PropertyName $NewValue # NOK

You can use PowerShell feature called Splatting in this case as explained by Don Jones himself here: Windows PowerShell: Splatting . 在这种情况下,您可以使用名为Splatting的 PowerShell功能,如Don Jones本人所解释的: Windows PowerShell:Splatting

In this you can define the parameters as a dictionary object of Property and Value pairs as below: 在此,您可以将参数定义为Property和Value对的字典对象,如下所示:

$parameters = @{$FirstPropertyName = $FirstValue; $SecondPropertyName = $SecondValue; $ThirdPropertyName = $ThirdValue}

Then you can pass this to your cmdlet using @ operator as shown below: 然后,您可以使用@运算符将其传递给cmdlet,如下所示:

Set-QadUser @parameters

Your complete working script will look as below: 您的完整工作脚本如下所示:

$property = 'MobilePhone' # OK
$value = ($User | get-QadUser -IncludedProperties $property).$property # OK

$parameters = @{$PropertyName = $NewValue}
$user | Set-QadUser @parameters # OK

Edit: I failed to notice earlier that PetSerAl already gave the answer in comments. 编辑:我之前没有注意到PetSerAl已在评论中给出答案。 I hope this answer also adds value overall. 我希望这个答案也能增加整体价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 PowerShell 变量作为命令参数? - How to use a PowerShell variable as command parameter? 如何运行与 PowerShell 别名同名的命令? - How to run a command with the same name as a PowerShell alias? Powershell 脚本参数作为变量名 - Powershell script parameter as variable name 如何从命令行运行 Powershell 脚本并将目录作为参数传递 - How to run a Powershell script from the command line and pass a directory as a parameter 如果命令行参数在Powershell中“存在”,如何设置变量? - How do I set a variable if a command line parameter is “present” in powershell? 如何在 shell 命令中运行的 powershell 脚本中使用变量? - How can I use a variable in a powershell script run in a shell command? 如何将命令 output 保存到变量中,以及如何将该变量用作 Powershell 中的命令参数? - How do I save a command output to a variable, and how do I use that variable as command parameter in Powershell? Powershell:同名参数为命令定义了多次 - Powershell: A parameter with the name was defined multiple times for the command 如何在 GitHub 工作流/操作中的 PowerShell 下运行名称中带有变量的脚本 - How run a script with variable in the name under PowerShell in GitHub workflow / actions 运行带有变量 -Path 参数的 Powershell 命令 - Running a Powershell command with a variable -Path parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM