編輯

共用方式為


Quickstart: Web API with PowerShell and Visual Studio Code

Learn to use PowerShell with the Dataverse Web API in Visual Studio Code. PowerShell is a powerful scripting language that can automate repetitive tasks and streamline workflows, making it an ideal tool for integrating with Dataverse. This quickstart helps you get started using PowerShell with the Dataverse Web API in Visual Studio Code. Visual Studio Code with PowerShell provides an alternative to using API clients like Postman or Insomnia.

In this quickstart, you learn how to:

  • Use Visual Studio Code with PowerShell to interactively authenticate with Dataverse without registering an application.
  • Compose requests to the Dataverse Web API by using the PowerShell Invoke-RestMethod cmdlet.

Note

This quickstart introduces only basic concepts. This introduction is enough for basic testing. After you complete the steps in this article, go to Use PowerShell and Visual Studio Code with the Dataverse Web API to learn more advanced capabilities that make you more productive, such as how to:

The instructions in this article should work for Windows, Linux, and macOS, but these steps are only tested on Windows. If changes are needed, please let us know by using the Feedback section at the bottom of this article.

Prerequisites

Don't proceed without confirming each of the following prerequisites is met.

Install or verify that the following are installed

Verify installation

  1. Open Visual Studio Code.

  2. In the Terminal menu, select New Terminal.

  3. In Visual Studio Code navigation pane, select the icon for the PowerShell extension.

  4. Copy and paste the following script in the Visual Studio Code terminal window:

    Write-Host 'PowerShell Version:'$PSVersionTable.PSVersion.ToString()
    Write-Host 'PowerShell Az version:'(Get-InstalledModule Az).Version
    
  5. Press Enter. The output should resemble the following:

    PowerShell Version: 7.4.0
    PowerShell Az version: 11.1.0
    

If you don't see results like this, install or update the prerequisites.

You'll also need

  • A valid user account for a Dataverse environment
  • The Url to the Dataverse environment you want to connect to. See View developer resources to learn how to find it. It looks something like this: https://yourorg.crm.dynamics.com/, where yourorg.crm is different.
  • Basic understanding of the PowerShell scripting language

Try it

  1. In Visual Studio Code, select File > New Text File, or press Ctrl+N to open a new file.

    You don't need to save the file.

  2. Copy and paste the following script into the new file.

    $environmentUrl = 'https://yourorg.crm.dynamics.com/' # change this
    ## Login if not already logged in
    if ($null -eq (Get-AzTenant -ErrorAction SilentlyContinue)) {
       Connect-AzAccount | Out-Null
    }
    
    # Get an access token
    $secureToken = (Get-AzAccessToken `
       -ResourceUrl $environmentUrl `
       -AsSecureString).Token
    
    # Convert the secure token to a string
    $token = ConvertFrom-SecureString `
       -SecureString $secureToken `
       -AsPlainText
    
    
    # Common headers
    $baseHeaders = @{
       'Authorization'    = 'Bearer ' + $token
       'Accept'           = 'application/json'
       'OData-MaxVersion' = '4.0'
       'OData-Version'    = '4.0'
    }
    # Invoke WhoAmI Function
    Invoke-RestMethod -Uri ($environmentUrl + 'api/data/v9.2/WhoAmI') -Method Get -Headers $baseHeaders
    | ConvertTo-Json
    

    Visual Studio Code should automatically detect it's a PowerShell script.

  3. Edit the $environmentUrl variable value (https://yourorg.crm.dynamics.com/) to match your Dataverse environment URL.

  4. Press F5, or use the Visual Studio Code Run > Start Debugging menu command.

    A browser window opens. In the browser window, enter or select the credentials you want to use to authenticate.

  5. Verify the output in the Visual Studio Code terminal window.

    At the bottom of the terminal, find the WhoAmIResponse complex type value expected for the WhoAmI function. It should look something like this:

    {
    "@odata.context": "https://yourorg.crm.dynamics.com/api/data/v9.2/$metadata#Microsoft.Dynamics.CRM.WhoAmIResponse",
    "BusinessUnitId": "11bb11bb-cc22-dd33-ee44-55ff55ff55ff",
    "UserId": "22cc22cc-dd33-ee44-ff55-66aa66aa66aa",
    "OrganizationId": "00aa00aa-bb11-cc22-dd33-44ee44ee44ee"
    }
    
  6. In the terminal window, type cls to clear the terminal content.

  7. Press F5, or use the Visual Studio Code Run > Start Debugging menu command to run the script again.

    Because you're already authenticated, the browser window doesn't open. You can continue to edit and run your script to try different requests.

How it works

This section describes the details of the PowerShell script included in the Try it section.

Authentication

The script uses the Az PowerShell module Get-AzTenant command to get tenants authorized for the current user. When you aren't signed in, this command returns an error. The script uses the -ErrorAction SilentlyContinue parameter to ignore the error and return nothing.

When the Get-AzTenant command doesn't return anything, the script uses the Connect-AzAccount command to open an interactive browser window where you can enter or select your credentials to sign in. Learn more about signing into Azure PowerShell interactively or noninteractively with a service principal.

Finally, the script uses the Get-AzAccessToken command with the -ResourceUrl $environmentUrl parameter to get a PSAccessToken instance, which contains a SecureString Token property that you can convert into an access token you can use to authenticate with Dataverse.

When you want to connect with a different set of credentials, use the Disconnect-AzAccount command.

Use Invoke-RestMethod with the WhoAmI function

After you set the access token to the $token variable, compose the request to Dataverse Web API and send it by using the Invoke-RestMethod cmdlet.

Set headers

All Dataverse Web API requests must include a set of common HTTP request headers, including an Authorization header that includes the access token value. Some operations require more headers. Learn more about Dataverse Web API request headers.

# Common headers
$baseHeaders = @{
   'Authorization'    = 'Bearer ' + $token
   'Accept'           = 'application/json'
   'OData-MaxVersion' = '4.0'
   'OData-Version'    = '4.0'
}

Send the request

The WhoAmI function is one of the simplest Dataverse operations you can perform. Because it's an OData function rather than an action, it requires the GET HTTP method. Learn more about Web API functions.

Use the Invoke-RestMethod cmdlet Uri, Method, and Headers parameters to send this request.

# Invoke WhoAmI Function
Invoke-RestMethod -Uri ($environmentUrl + 'api/data/v9.2/WhoAmI') -Method Get -Headers $baseHeaders
| ConvertTo-Json

For operations that use POST or PATCH HTTP methods, set the Body parameter to send the JSON payload.

The ConvertTo-Json cmdlet converts the object returned to a JSON-formatted string that is easy to see in the terminal.

If you want to capture only the UserId property of the response, use the following script:

# Get UserId
$userId = (
   Invoke-RestMethod `
   -Uri ($environmentUrl + 'api/data/v9.2/WhoAmI') `
   -Method 'Get' `
   -Headers $baseHeaders
   ).UserId
Write-Host $userId

Troubleshooting

Make sure you verify all the required programs are installed as described in Verify installation.

The following situations can cause the instructions in this quick start to fail:

Nothing happens when I press F5

Make sure that your keyboard has function keys enabled by pressing the F-Lock, Fn Lock, or Function Lock key.

You can also use the Visual Studio Code Run > Start Debugging menu command instead.

No such host is known

If you see this error after running the script:

Invoke-RestMethod: untitled:Untitled-1:14:1
Line |
14 |  Invoke-RestMethod -Uri ($environmentUrl + 'api/data/v9.2/WhoAmI') -Me …
   |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   | No such host is known.

Check that the $environmentUrl represents an environment you have access to. Make sure you changed it from the default value (https://yourorg.crm.dynamics.com/).

The user is not a member of the organization

If you see this error after running the script:

Invoke-RestMethod: untitled:Untitled-1:14:1                                                                             
Line |
14 |  Invoke-RestMethod -Uri ($environmentUrl + 'api/data/v9.2/WhoAmI') -Me …
   |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   |  {   "error": {     "code": "0x80072560",     "message": "The user is not a member of the organization."   } }

Make sure that the account you select in the browser window is the account that has access to the Dataverse environment specified by the $environmentUrl parameter.

If you're using a different set of credentials than you used before, use the Disconnect-AzAccount command in the terminal window.

WARNING: TenantId '<your tenant id>' contains more than one active subscription

When you run the script for the first time and sign in by using the browser, you might get this warning:

WARNING: TenantId '<your tenant id>' contains more than one active subscription. First one will be selected for further use. 
To select another subscription, use Set-AzContext. 
To override which subscription Connect-AzAccount selects by default, use `Update-AzConfig -DefaultSubscriptionForLogin 00000000-0000-0000-0000-000000000000`. 
Go to https://go.microsoft.com/fwlink/?linkid=2200610 for more information.

You can ignore this warning. These requests don't require a subscription.

Next steps

Learn more advanced capabilities to be more productive using PowerShell and Visual Studio Code with the Dataverse Web API, such as how to:

Now that you can authenticate and send Dataverse Web API requests by using PowerShell, try other Web API operations.

Learn more about Dataverse Web API capabilities by understanding the service documents.