调用VSTS API时传递个人访问令牌(PAT)的方法
Got it, since you're stuck on PowerShell 2.0 without access to Invoke-RestMethod, here's a reliable way to authenticate your VSTS API requests using [System.Net.WebRequest] with a Personal Access Token (PAT):
How VSTS PAT Authentication Works
VSTS uses Basic Auth for PATs, but with a twist: you can use an empty username (or any placeholder, since VSTS ignores it) and your PAT as the password. We just need to encode this combination into a Base64 string and attach it to the Authorization header of your request.
Step-by-Step Code Implementation
Define your PAT and API endpoint
Replace the placeholders with your actual PAT and VSTS API URL:$pat = "your-actual-pat-here" $apiUrl = "https://dev.azure.com/your-org-name/your-project-name/_apis/build/packages?api-version=6.0"Generate the Base64-encoded auth string
PowerShell 2.0 doesn't have some of the newer encoding shortcuts, so we'll use .NET classes directly:# Combine empty username + PAT (format: ":<your-pat>") $authString = ":" + $pat # Convert to ASCII byte array $authBytes = [System.Text.Encoding]::ASCII.GetBytes($authString) # Encode to Base64 $authBase64 = [System.Convert]::ToBase64String($authBytes) # Build the full Authorization header value $authHeader = "Basic " + $authBase64Configure the WebRequest
Set up the request with the auth header and necessary content type settings:# Create the WebRequest instance $webRequest = [System.Net.WebRequest]::Create($apiUrl) # Set request method (use POST if you're sending data, GET for queries) $webRequest.Method = "GET" # Add the Authorization header $webRequest.Headers.Add("Authorization", $authHeader) # Tell the API we accept JSON responses $webRequest.Accept = "application/json"Send the request and process the response
Handle the response (and errors) properly, including JSON parsing compatible with PowerShell 2.0:try { # Get the response from the server $response = $webRequest.GetResponse() # Read the response stream $responseStream = $response.GetResponseStream() $streamReader = New-Object System.IO.StreamReader($responseStream) $responseContent = $streamReader.ReadToEnd() # Clean up resources $streamReader.Close() $response.Close() # Parse JSON (PowerShell 2.0-compatible method) # Load the required assembly if it's not already loaded [void][System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") $jsonSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer $parsedResult = $jsonSerializer.DeserializeObject($responseContent) # Output the parsed result $parsedResult } catch { # Handle errors gracefully Write-Error "Request failed: $($_.Exception.Message)" if ($_.Exception.Response) { $errorStream = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) $errorContent = $errorStream.ReadToEnd() Write-Error "Error details: $errorContent" $errorStream.Close() } }
Key Notes
- PAT Permissions: Make sure your PAT has the necessary permissions (e.g.,
Build (Read)for querying build packages). - Username Placeholder: Using an empty username (
":" + $pat) works perfectly—VSTS only validates the PAT portion of the auth string. - JSON Parsing: PowerShell 2.0 doesn't include
ConvertFrom-Json, so we use .NET'sJavaScriptSerializeras a fallback.
内容的提问来源于stack exchange,提问作者s-a-n

