简体   繁体   中英

Use result of one query as argument of a command (on a single line)

Administering AzureAD, Exchange Online, Teams etc. from PowerShell, I like to save one-liners in a text file that I later call on, but sometimes, the commands require an object ID when all I know is the object's name.

For instance, the cmdlet, Add-TeamUser , lets me add a user to a Team group. However, it requires the group ID when I want to supply the name. I can get the group ID from the name via:

Get-Team | Where-Object {$_.DisplayName -eq "Produce Sales"} | select GroupId

Output (partially obscured):

在此处输入图像描述

Is it possible to use that query inline with Add-TeamUser ? Something like:

Add-TeamUser -GroupId {the-above-query} -User someone@somewhere.com

More than likely, the cmdlet of Add-TeamUser accepts input by pipeline. Id run a Get-Help Add-TeamUser -Full to see what type of values it accepts so you can just pipe to it. Alternatively, you can just assign the value to a Variable and send it to the next command. In this scenario, we have an array of values and we loop through each one, grabbing JUST the ID, and then adding them by the ID:

$ListOfNames = @("Produce Sales","Shoe Sales", "ETC")
    Foreach($name in $ListOfNames){
        $GroupID = Get-Team | Where-Object {$_.DisplayName -eq "$name"} | Select-Object -ExpandProperty GroupId
            Add-TeamUser -GroupId $GroupID -User someone@somewhere.com
                        }

And another way it can be used is to pass it to the foreach-object cmdlet and let it take the value from the pipeline for you. It can also be used just at the top sample code did:

Get-Team | Where-Object {$_.DisplayName -eq "Produce Sales"} | Select-Object -ExpandProperty GroupId | ForEach-Object -Process{
     Add-TeamUser -GroupId $_ -User someone@somewhere.com}               

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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