Introdução ao SDK do Microsoft Graph PowerShellGet started with the Microsoft Graph PowerShell SDK
Neste guia, você usará o SDK do Microsoft Graph PowerShell para realizar algumas tarefas básicas.In this guide you'll use the Microsoft Graph PowerShell SDK to perform some basic tasks. Se você ainda não instalou o SDK, faça isso antes de seguir este guia.If you haven't already installed the SDK, please do so before following this guide.
Versão da APIAPI version
Por padrão, o SDK usa a API REST do Microsoft Graph v 1.0.By default, the SDK uses the Microsoft Graph REST API v1.0. Você pode alterar isso usando o Select-MgProfile
comando.You can change this by using the Select-MgProfile
command.
Select-MgProfile -Name "beta"
AutenticaçãoAuthentication
O SDK do PowerShell oferece suporte a dois tipos de autenticação: acesso delegado e acesso somente de aplicativo.The PowerShell SDK supports two types of authentication: delegated access, and app-only access. Neste guia, você usará o acesso delegado para fazer logon como um usuário, conceder consentimento ao SDK para atuar em seu nome e chamar o Microsoft Graph.In this guide, you will use delegated access to login as a user, grant consent to the SDK to act on your behalf, and call the Microsoft Graph.
Para obter detalhes sobre como usar o acesso somente de aplicativo para cenários autônomos, consulte usar a autenticação somente aplicativo com o SDK do PowerShell do Microsoft Graph.For details on using app-only access for unattended scenarios, see Use app-only authentication with the Microsoft Graph PowerShell SDK.
Determinar os escopos de permissão necessáriosDetermine required permission scopes
Cada API no Microsoft Graph é protegida por um ou mais escopos de permissão.Each API in the Microsoft Graph is protected by one or more permission scopes. O logon do usuário deve ser consentido em um dos escopos necessários para as APIs que você planeja usar.The user logging in must consent to one of the required scopes for the APIs you plan to use. Neste exemplo, usaremos as seguintes APIs.In this example, we'll use the following APIs.
- Listar usuários para encontrar a ID de usuário do usuário conectadoList users to find the user ID of the logged-in user
- Liste joinedTeams para obter as equipes das quais o usuário é membro.List joinedTeams to get the Teams the user is a member of.
- Listar canais para obter os canais de uma equipe.List channels to get the channels in a Team.
- Enviar mensagem para enviar uma mensagem para um canal de equipe.Send message to send a message to a Team channel.
O User.Read.All
escopo de permissão habilitará as duas primeiras chamadas, e o Group.ReadWrite.All
escopo habilitará o restante.The User.Read.All
permission scope will enable the first two calls, and the Group.ReadWrite.All
scope will enable the rest. Essas permissões exigem uma conta de administrador.These permissions require an admin account.
EntrarSign in
Use o Connect-MgGraph
comando para entrar com os escopos necessários.Use the Connect-MgGraph
command to sign in with the required scopes. Você precisará entrar com uma conta de administrador para se concordar com os escopos necessários.You'll need to sign in with an admin account to consent to the required scopes.
Connect-MgGraph -Scopes "User.Read.All","Group.ReadWrite.All"
O comando solicita que você acesse uma página da Web para entrar usando um código de dispositivo.The command prompts you to go to a web page to sign in using a device code. Depois de fazer isso, o comando indica êxito com uma Welcome To Microsoft Graph!
mensagem.Once you've done that, the command indicates success with a Welcome To Microsoft Graph!
message. Você só precisa fazer isso uma vez por sessão.You only need to do this once per session.
Dica
Você pode adicionar permissões adicionais repetindo o Connect-MgGraph
comando com os novos escopos de permissão.You can add additional permissions by repeating the Connect-MgGraph
command with the new permission scopes.
Chamar o Microsoft GraphCall Microsoft Graph
Agora que você está conectado, você pode começar a fazer chamadas para o Microsoft Graph.Now that you're signed in, you can start making calls to Microsoft Graph.
Obter o usuário conectadoGet the signed-in user
Nesta seção, você localizará o usuário conectado e obterá sua ID de usuário.In this section you'll locate the signed-in user and get her user ID. Você precisará usar como um parâmetro para os outros comandos que você usará posteriormente.You'll need that to use as a parameter to the other commands you'll use later. Inicie executando o seguinte comando.Start by running the following command.
Get-MgUser
Isso gera uma listagem de usuários na sua organização do Microsoft 365.This outputs a listing of users in your Microsoft 365 organization.
Id DisplayName Mail UserPrincipalName
-- ----------- ---- -----------------
88d1ba68-8ff5-4de2-90ed-768c00abcfae Conf Room Adams Adams@contoso.onmicrosoft.com Adams@contoso.…
3103c7b9-cfe6-4cd3-a696-f88909b9a609 Adele Vance AdeleV@contoso.OnMicrosoft.com AdeleV@contoso…
da3a885e-2d97-41de-9347-5271ef321b58 MOD Administrator admin@contoso.OnMicrosoft.com admin@contoso.…
e0c6ee40-e105-476d-9597-acd061d21fcb Alex Wilber AlexW@contoso.OnMicrosoft.com AlexW@contoso.…
17c6bdee-8ed3-49af-a65e-71b64cca8382 Allan Deyoung AllanD@contoso.OnMicrosoft.com AllanD@contoso…
e5b78950-27cd-4f01-b083-eab4da97ca6a Conf Room Baker Baker@contoso.onmicrosoft.com Baker@contoso.…
40467725-1a58-495d-9e2f-5970c6306d8d Bianca Pisani BiancaP@contoso…
ce73bdb5-bf12-405e-ab85-40122fdd6eb7 Brian Johnson (TAILSPIN) BrianJ@contoso.onmicrosoft.com BrianJ@contoso…
df1347a3-7ce7-4b4d-8aab-7c65b5c907b9 Cameron White CameronW@contoso…
Você pode usar um filtro OData para ajudar a localizar o usuário específico desejado.You can use an OData filter to help locate the specific user you want. Execute o comando a seguir, substituindo Megan Bowen
pelo nome de exibição do usuário com o qual você entrou.Run the following command, replacing Megan Bowen
with the display name of the user you signed in with.
$user = Get-MgUser -Filter "displayName eq 'Megan Bowen'"
Verifique se funcionou, inserindo o seguinte.Verify that worked by entering the following.
$user.DisplayName
Listar as equipes Unidas do usuárioList the user's joined Teams
Agora use a ID do usuário como um parâmetro para o Get-MgUserJoinedTeam
comando.Now use the user's ID as a parameter to the Get-MgUserJoinedTeam
command.
Get-MgUserJoinedTeam -UserId $user.Id
Assim como o Get-MgUser
comando, isso fornece uma lista de equipes.Just like the Get-MgUser
command, this gives a list of Teams. Selecione uma das equipes Unidas do usuário e use seu DisplayName
para filtrar a lista.Select one of the user's joined Teams and use its DisplayName
to filter the list.
$team = Get-MgUserJoinedTeam -UserId $user.Id -Filter "displayName eq 'Sales and Marketing'"
Listar Canais de equipeList Team channels
Agora use a ID da equipe como um parâmetro para o Get-MgTeamChannel
comando, seguindo um padrão semelhante de listar todos os canais e, em seguida, filtrando a lista para obter o canal específico desejado.Now use the Team's ID as a parameter to the Get-MgTeamChannel
command, following a similar pattern of listing all channels, then filtering the list to get the specific channel you want.
Get-MgTeamChannel -TeamId $team.Id
$channel = Get-MgTeamChannel -TeamId $team.Id -Filter "displayName eq 'General'"
Enviar uma mensagemSend a message
Agora que você tem a ID da equipe e a ID do canal, é possível postar uma mensagem para o canal.Now that you have both the Team ID and the channel ID, you can post a message to the channel. Use o comando a seguir para enviar a mensagem.Use the following command to send the message.
New-MgTeamChannelMessage -TeamId $team.Id -ChannelId $channel.Id -Body @{ Content="Hello World" }
Este comando difere dos comandos anteriores que você usou.This command differs from the previous commands you used. Em vez de apenas consultar dados, ele está realmente criando algo.Instead of just querying data, it's actually creating something. No Microsoft Graph, isso é convertido em HTTP POST
e requer um objeto no corpo dessa postagem.In Microsoft Graph, this translates to an HTTP POST
, and it requires an object in the body of that post. Nesse caso, o objeto é um chat.In this case, the object is a chatMessage. Observe que o -Body
parâmetro para o comando é mapeado para a body
propriedade em chatMessage
.Note that the -Body
parameter to the command maps to the body
property on chatMessage
. Outras propriedades são mapeadas de forma semelhante, para que você possa alterar a mensagem enviada.Other properties are mapped in a similar way, so you can change the message you send. Por exemplo, para enviar uma mensagem urgente, use o comando a seguir.For example, to send an urgent message use the following command.
New-MgTeamChannelMessage -TeamId $team.Id -ChannelId $channel.Id -Body @{ Content="Hello World" } -Importance "urgent"
SairSign out
Use o Disconnect-MgGraph
comando para sair.Use the Disconnect-MgGraph
command to sign out.
Disconnect-MgGraph