简体   繁体   English

执行存储在 powershell object 中的 cmdlet 列表

[英]Executing a list of cmdlets stored in an powershell object

I have list of cmdlets stored in a variable $commands and this is the output of it:我有存储在变量$commands中的 cmdlet 列表,这是它的 output:

PS C:\Windows\system32> $commands

Get-AzCloudService

Get-AzCloudService_Get

Get-AzCloudService_GetViaIdentity

Get-AzCloudService_List

Get-AzCloudService_List1

How can I execute the commands in $commands one by one.如何一一执行$commands中的命令。

I have tried to execute this:我试图执行这个:

$commands | ForEach-Object{$_}

and this:和这个:

$commands | ForEach-Object{Invoke-Command -ScriptBlock {$_}}

But both the above lines just displays the cmdlets and doesn't execute them.但以上两行都只显示 cmdlet 而不会执行它们。 I have searched everywhere to get it but could not find it.我到处寻找它,但找不到它。

You almost got it.你几乎明白了。 You are just missing out the call operator & .您只是错过了呼叫运算符&

$commands | ForEach-Object { & $_ }

To call all commands with the same arguments, add them as usual:要使用相同的 arguments 调用所有命令,请照常添加它们:

$commands | ForEach-Object { & $_ -arg1name arg1value -arg2name arg2value }

You might want to have a list of commands and accompanying arguments.您可能想要一个命令列表和随附的 arguments。 For this you could use splatting .为此,您可以使用splatting

$commands = @(
     @{ command = 'foo'; args = @{ arg1name = arg1value; arg2name = arg2value } }
     @{ command = 'bar'; args = @{ arg1name = arg1value; arg2name = arg2value } }
)

$commands | ForEach-Object { 
    $theArgs = $_.args
    & $_.command @theArgs
}

Note that I had to assign the arguments to a variable first, because splatting does not work with member access.请注意,我必须首先将 arguments 分配给一个变量,因为 splatting 不适用于成员访问。 It requires a single variable name after the @ .它需要在@之后有一个变量名。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM