Assigning Intune scope tags to Azure Azure AD group - azure

I cannot figure this on out. I need a way to assign Endpoint Manager's Scope tags to an Azure AD group using Microsoft Graph and PowerShell.
Under the portal this is done under Endpoint Manager\Tenant Administration\Roles\Scope (Tags). Then clicking on the Tag and tgo to assignments and browse to Azure AD group.
Since its under Roles, I'm assuming it falls under the roleAssignment or roleScopeTag resource types?
I have thoroughly read all documentation for the REST api and I have also attempted to do this via Microsoft.Graph.Intune modules but still cannot find a suitable cmdlet that will do this. Am I missing something?
Here is the current code I have built following this document
FIRST let's assume I have the correct tag id and azure ad group object id.
$ScopeTagId = 2
$TargetGroupIds = #()
$TargetGroupIds += '687c08f1-e78f-4506-b4a6-dfe35a05d138'
$graphApiVersion = "beta"
$Resource = "deviceManagement/roleScopeTags"
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name 'assignments' -Value #($TargetGroupIds)
$JSON = $object | ConvertTo-Json
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$ScopeTagId/assign"
Invoke-RestMethod -Method Post -Uri $uri -Headers $global:authToken -Body $JSON
No success. I then thought that since the create roleScopeTag API doesn't have an assignment property in the request body, this must be done using the update method, but that doesn't have it in there either. The only one I read was to use the assign action and in the documentation example it shows the roleScopeTagAutoAssignment URI, so I went down that rabbit hole:
$ScopeTagId = 2
$TargetGroupIds = #()
$TargetGroupIds += '687c08f1-e78f-4506-b4a6-dfe35a05d138'
$graphApiVersion = "beta"
$Resource = "deviceManagement/roleScopeTags"
$AutoTagObject = #()
foreach ($TargetGroupId in $TargetGroupIds) {
#Build custom object for assignment
$AssignmentProperties = "" | Select '#odata.type',id,target
$AssignmentProperties.'#odata.type' = '#microsoft.graph.roleScopeTagAutoAssignment'
$AssignmentProperties.id = $TargetGroupId
#Build custom object for target
$targetProperties = "" | Select "#odata.type",deviceAndAppManagementAssignmentFilterId,deviceAndAppManagementAssignmentFilterType
$targetProperties."#odata.type" = "microsoft.graph.deviceAndAppManagementAssignmentTarget"
$targetProperties.deviceAndAppManagementAssignmentFilterId = $TargetGroupId
$targetProperties.deviceAndAppManagementAssignmentFilterType = 'include'
#add target object to assignment
$AssignmentProperties.target = $targetProperties
$AutoTagObject += $AssignmentProperties
}
#build body object
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name 'assignments' -Value #($AutoTagObject)
$JSON = $object | ConvertTo-Json
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$ScopeTagId/assign"
Invoke-RestMethod -Method Post -Uri $uri -Headers $global:authToken -Body $JSON
The error I get back is something like: "Property target in payload has a value that does not match schema.","innerError":{"date":"2022-01-27T16:28:34","request-id":"75626c4d-f09b-438e-8b0f-0b2928ac23ce","client-request-id":"75626c4d-f09b-438e-8b0f-0b2928ac23ce" which I assume is the odata.type object i'm calling "microsoft.graph.deviceAndAppManagementAssignmentTarget"
There is a second post method in the documentations via roledefinition URI which seems like an unnecessary step, but I tried that too with no success.
I do not know if any of this is correct. I understand the API calls for others pretty well and I have been able to successfully add Tags for Custom Roles and their assignments using graph; I just can't seem to find the right combination of URI and JSON body for scope tags themselves...if it even exists. :(
Any ideas, please share some code snippets if you can. THANKS!

I found the correct URI and request body
If can be generated like this:
$ScopeTagId = 2
$TargetGroupIds = #()
$TargetGroupIds += '687c08f1-e78f-4506-b4a6-dfe35a05d138'
$graphApiVersion = "beta"
$Resource = "deviceManagement/roleScopeTags"
$AutoTagObject = #()
#TEST $TargetGroupId = $TargetGroupIds[0]
foreach ($TargetGroupId in $TargetGroupIds) {
#Build custom object for assignment
$AssignmentProperties = "" | Select id,target
$AssignmentProperties.id = ($TargetGroupId + '_' + $ScopeTagId)
#Build custom object for target
$targetProperties = "" | Select "#odata.type",deviceAndAppManagementAssignmentFilterId,deviceAndAppManagementAssignmentFilterType,groupId
$targetProperties."#odata.type" = "microsoft.graph.groupAssignmentTarget"
$targetProperties.deviceAndAppManagementAssignmentFilterId = $null
$targetProperties.deviceAndAppManagementAssignmentFilterType = 'none'
$targetProperties.groupId = $TargetGroupId
#add target object to assignment
$AssignmentProperties.target = $targetProperties
$AutoTagObject += $AssignmentProperties
}
#build body object
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name 'assignments' -Value #($AutoTagObject)
$JSON = $object | ConvertTo-Json -Depth 10
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$ScopeTagId/assign"
Invoke-RestMethod -Method Post -Uri $uri -Headers $global:authToken -Body $JSON -ErrorAction Stop
The Json request body would look like this:
{
"assignments": [
{
"id": "b25c80e3-78cc-4b7c-888e-fc50dcc6b582_2",
"target": {
"#odata.type": "microsoft.graph.groupAssignmentTarget",
"deviceAndAppManagementAssignmentFilterId": null,
"deviceAndAppManagementAssignmentFilterType": "none",
"groupId": "b25c80e3-78cc-4b7c-888e-fc50dcc6b582"
}
}
]
}
Nowhere is this documented...

Related

Issue with Automation Accounts>Runbooks: The remote server returned an error: (401) Unauthorized

I am facing on an issue with azure script. I created a runbook in automation accounts and I gave to new app the contributor rights on subscription, but when I run the code I see:
The remote server returned an error: (401) Unauthorized. Invoke-WebRequest : The remote server returned an error: (401) Unauthorized. At line:82 char:13 + $All_BSOD = Invoke-WebRequest -Uri $Top50_BSOD_URL -Method GET -Heade ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand .
At below there are the code:
# Function to send Teams notif
Function Send_Notif
{
param(
$Text,
$Title
)
$Body = #{
'text'= $Text
'Title'= $Title
'themeColor'= "$Color"
}
$Params = #{
Headers = #{'accept'='application/json'}
Body = $Body | ConvertTo-Json
Method = 'Post'
URI = $Webhook_URL
}
Invoke-RestMethod #Params
}
#*****************************************************************
# Part to fill
#*****************************************************************
# Teams webhoot link
$Webhook_URL = "personal link"
# Choose the top x devices (default is 50)
$Top_count = 50
# Teams notif design
$Notif_Title = "Top 50 devices with BSOD"
$Notif_Message = "Here is the list of top 50 devices with BSOD on the last 30 days"
$Color = "2874A6"
#*****************************************************************
# Getting a token
$url = $env:IDENTITY_ENDPOINT
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER)
$headers.Add("Metadata", "True")
$body = #{resource='https://graph.microsoft.com/' }
$script:accessToken = (Invoke-RestMethod $url -Method 'POST' -Headers $headers -ContentType 'application/x-www-form-urlencoded' -Body $body ).access_token
# Authentication
Connect-AzAccount -Identity
$headers = #{'Authorization'="Bearer " + $accessToken}
# Graph URL to use
$Top50_BSOD_URL = "https://graph.microsoft.com/beta/deviceManagement/userExperienceAnalyticsDevicePerformance?dtFilter=all&`$orderBy=blueScreenCount%20desc&`$top=$Top_count&`$filter=blueScreenCount%20ge%201%20and%20blueScreenCount%20le%2050"
$StartupHistory_url = "https://graph.microsoft.com/beta/deviceManagement/userExperienceAnalyticsDeviceStartupHistory?" + '$filter=deviceId%20eq%20%27' + "$DeviceID%27"
# Getting BSOD info
$All_BSOD = Invoke-WebRequest -Uri $Top50_BSOD_URL -Method GET -Headers $Headers -UseBasicParsing
$All_BSOD_JsonResponse = ($All_BSOD.Content | ConvertFrom-Json)
$Get_All_BSOD = $All_BSOD_JsonResponse.value
$BSOD_Array = #()
ForEach($BSOD in $Get_All_BSOD)
{
$Device_Model = $BSOD.model
$Device_Name = $BSOD.deviceName
$BSOD_Count = $BSOD.blueScreenCount
$DeviceID = $BSOD.id
$Get_StartupHistory = Invoke-WebRequest -Uri $StartupHistory_url -Method GET -Headers $Headers -UseBasicParsing
$Get_BSOD_JsonResponse = ($Get_StartupHistory.Content | ConvertFrom-Json)
$Get_BSOD = ($Get_BSOD_JsonResponse.value | Where {$_.restartCategory -eq "blueScreen"})[-1]
$Last_BSOD_Date = [datetime]($Get_BSOD.startTime)
$Last_BSOD_Code = $Get_BSOD.restartStopCode
$OS = $Get_BSOD.operatingSystemVersion
$BSOD_Obj = New-Object PSObject
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Device" -Value $Device_Name
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Model" -Value $Device_Model
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Count" -Value $BSOD_Count
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "OS version" -Value $OS
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Last BSOD" -Value $Last_BSOD_Date
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Last code" -Value $Last_BSOD_Code
$BSOD_Array += $BSOD_Obj
}
$BSOD_Table = $BSOD_Array | ConvertTo-HTML -Fragment
$BSOD_Table = $BSOD_Table.Replace("<table>","<table border='1'>")
$Text_Message = "$Notif_Message<br><br>
$BSOD_Table
"
Send_Notif -Text $Text_Message -Title $Notif_Title | out-null
Anybody can help me?
thank you
PS: this is the original webpage text
My aim is to get a notification to all bsod\devices in my enviroment

Is there a better way to get users information and their manager for a specific MemberOf Group in Graph API Powershell

Is there a better way to get users' information and their manager for a specific MemberOf Group in Graph API in Powershell? I have written below, it works but doesn't seem to be the best way to do this. I am new to this so please take it easy on me!
Ideally, I would like ALL fields from the Get-MgUser with the user's Manager and the specific MgUserMemberOf group I am searching for at the end of the CSV export, but not sure if it is possible.
if (Get-InstalledModule Microsoft.Graph) {
# Connect to MS Graph $appid = 'BLAH' $tenantid = 'BLAH' $secret = 'BLAH'
$body = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $appid
Client_Secret = $secret } $connection = Invoke-RestMethod `
-Uri https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token `
-Method POST `
-Body $body $token = $connection.access_token Connect-MgGraph -AccessToken $token
### Comment out below to use the production version of Azure AD
Select-MgProfile -Name "beta"
$users = Get-MgUser -Filter "startsWith(DisplayName, 'Joe Bloggs')" foreach($Id in $users)
{
$MemberOf = Get-MgUserMemberOf -UserId $CurrentID | Where {$_.AdditionalProperties['displayName'] -like "*VIP*"} | Select id, #{E={$_.additionalProperties['displayName']}}
$UserManager = Get-MgUserManager -UserId $CurrentID | Select id, #{E={$_.additionalProperties['displayName']}}
$Result = "$($users.Id) , ""$($users.DisplayName)"", ""$($UserManager.'$_.additionalProperties[''displayName'']')"", ""$($MemberOf.'$_.additionalProperties[''displayName'']')"""
write-host $Result
Add-Content "C:\Temp\Result.csv" $Result
} }
Current Export
00000000-56fa-4638-9ff6-1dc85d3c9735 , "DISPLAY NAME", "MANAGER", "Member Of GROUP"
Your code is very confusing but I think what you're looking for is something similar to this:
if (Get-InstalledModule Microsoft.Graph) {
$params = #{
Uri = "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/tokenMethod"
Method = 'POST'
Body = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $appid
Client_Secret = $secret
}
}
$connection = Invoke-RestMethod #params
Connect-MgGraph -AccessToken $connection.access_token
Select-MgProfile -Name "beta"
Get-MgUser -Filter "startsWith(DisplayName, 'Joe Bloggs')" | ForEach-Object {
[pscustomobject]#{
Id = $_.Id
DisplayName = $_.DisplayName
Manager = (Get-MgUserManager -UserId $_).additionalProperties['displayName']
MemberOf = (Get-MgUserMemberOf -UserId $_).Where{ $_.AdditionalProperties['displayName'] -like "*VIP*" }.additionalProperties['displayName']
}
} | Export-Csv "C:\Temp\Result.csv" -NoTypeInformation
}

Can we add label to tiles on Azure Dashboard [duplicate]

Is it possible to show custom information in azure dashboards?
I was searching on how to add custom content in azure dashboards but did not find anything. The only thing close was the markdown tile which allows html to be displayed.
With this in mind and after a lot of digging I found a solution:
Basically we needed a custom tile that displays data retrieved from our REST api.
1. Create a new, empty 'Markdown' tile on a new or existing dashboard, give it a 'Title'
2. Share the dashboard
3. Navigate to All services, Filter by 'dashboards' in the ResourceGroup filter
- Click on the dashboard which contains the 'Markdown' tile
- Take a note of the 'RESOURCE ID'
In our scenario, we used Azure Automation Runbooks. In this scenario we utilized the Azure Resource Manager REST api.
4. Create a new RunBook [Powershell Runbook]
The following steps concern the following:
- Login to the ResourceManagerAPI
- Get Azure Resource by ID [The Resource ID above]
- Update Azure Resource by ID [The Resource ID above]
Before we continue, we need to get our client credentials. To do so:
- Click on Cloud Shell in the Portal Menu bar
- Type 'az'
- Type 'az ad sp create-for-rpac -n "runbooks"' //runbooks is just a name, feel free to input a different string
- The above command should list out the credentials needed. If an error occurs, kindly contact your Azure admin and run it from their account.
5. In your empty powershell runbook, add the following 2 variables:
$ExpectedTileName = "Extension/HubsExtension/PartType/MarkdownPart"
$MarkdownTileTitle = "<The Markdown title you've set in the first step>"
6. Getting the Access_Token [The variables <> represent the values retrieved from the previous step]
#Get Bearer Token
$TenantId = '<Your tenantID>'
$LoginUri = "https://login.microsoftonline.com/"+$TenantId+"/oauth2/token"
$params = #{
"grant_type"="client_credentials";
"client_id"="<appId>";
"client_secret"="<password>";
"resource"="https://management.azure.com";
}
$LoginResponse = Invoke-RestMethod -Uri $LoginUri -Method Post -Body $params
$Access_Token = $LoginResponse.access_token;
$Access_TokenString = "Bearer " + $Access_Token
7. Getting the DashboardResource by ResourceID:
#Get Resource
$RMUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$DashboardResource = (Invoke-RestMethod -Uri $RMUri -Method Get -Headers #{'Authorization'=$Access_TokenString}) | ConvertTo-Json -Depth 100 | ConvertFrom-Json
8. Looping through all tiles within the dashboard. Please note that tiles are not contained within an array, thus you may need to increase/decrease the length of the for loop.
#Loop through all tiles within the dashboard
$Parts = $DashboardResource.properties.lenses.0.0.parts
For ($i=0; $i -lt 200; $i++)
{
$Part = $Parts | Select-Object -Property $i.toString()
if($Part.$i)
{
if($Part.$i.metadata.type -eq $ExpectedTileName -And $Part.$i.metadata.settings.content.settings.title -eq $MarkdownTileTitle)
{
$Part.$i.metadata.settings.content.settings.content = <CustomValue ex: invoke a get request to your api>
}
}
else
{
break
}
}
9. Finally we need to update the dashboard resource
#Update Resource
$UpdateUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$JsonValue = $DashboardResource | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $UpdateUri -Method Put -Headers #{'Authorization'=$Access_TokenString; 'Content-type'='application/json'} -Body $JsonValue
To sum it up:
$ExpectedTileName = "Extension/HubsExtension/PartType/MarkdownPart"
$MarkdownTileTitle = "<The Markdown title you've set in the first step>"
#Get Bearer Token
$TenantId = '<Your subscriptionID>'
$LoginUri = "https://login.microsoftonline.com/"+$TenantId+"/oauth2/token"
$params = #{
"grant_type"="client_credentials";
"client_id"="<appId>";
"client_secret"="<password>";
"resource"="https://management.azure.com";
}
$LoginResponse = Invoke-RestMethod -Uri $LoginUri -Method Post -Body $params
$Access_Token = $LoginResponse.access_token;
$Access_TokenString = "Bearer " + $Access_Token
#Get Resource
$RMUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$DashboardResource = (Invoke-RestMethod -Uri $RMUri -Method Get -Headers #{'Authorization'=$Access_TokenString}) | ConvertTo-Json -Depth 100 | ConvertFrom-Json
#Loop through all tiles within the dashboard
$Parts = $DashboardResource.properties.lenses.0.0.parts
For ($i=0; $i -lt 200; $i++)
{
$Part = $Parts | Select-Object -Property $i.toString()
if($Part.$i)
{
if($Part.$i.metadata.type -eq $ExpectedTileName -And $Part.$i.metadata.settings.content.settings.title -eq $MarkdownTileTitle)
{
$Part.$i.metadata.settings.content.settings.content = <CustomValue ex: invoke a get request to your api>
}
}
else
{
break
}
}
#Update Resource
$UpdateUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$JsonValue = $DashboardResource | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $UpdateUri -Method Put -Headers #{'Authorization'=$Access_TokenString; 'Content-type'='application/json'} -Body $JsonValue
Conclusion
With this newly created runbook we can now schedule it to run every 1 hour. In our case, 1 hour was too much. The following article shows how we can schedule the runbook to run every 1 minute.
https://blogs.technet.microsoft.com/stefan_stranger/2017/06/21/azure-scheduler-schedule-your-runbooks-more-often-than-every-hour/

Is there a way to filter issues in GitLab by whether or not they have a related merge request?

I have a number of issues assigned to me to work on, and I've made merge requests to fix many of them. I am looking for a query that would let me filter out issues with a related merge request.
The GitLab instance I'm using is at v14.4.2.
I've looked in the docs for both basic search and advanced search, but can't figure out a good query for this.
The equivalent query in GitHub would be is:issue is:open assignee:legowerewolf -linked:pr
As of writing, that's not possible.
Generally, if a feature is not listed in the docs, then it hasn't been implemented. You can search for and existing feature request in the GitLab issue tracker (though I didn't find one) or file a feature request.
As per #Arty-chan above, there's no built-in way to do this. After futzing around in PowerShell and with the API for a bit, I came up with this:
$GitlabToken = '[your GitLab PAT with API read access]'
$APIRoot = 'https://[your GitLab server here]/api/v4'
$TokenHeader = #{
"PRIVATE-TOKEN" = $GitlabToken
}
$User = Invoke-RestMethod -Method Get -Uri "$APIRoot/user" -Headers $TokenHeader
$UserOpenIssues = Invoke-RestMethod -Method Get -Uri "$APIRoot/issues" -Headers $TokenHeader -Body #{
assignee_id = $User.id
state = "opened"
scope = "all"
}
foreach ($Issue in $UserOpenIssues) {
$Issue | Add-Member -MemberType NoteProperty -Name "related_merge_requests" -Value (
Invoke-RestMethod -Method Get -Uri "$APIRoot/projects/$($Issue.project_id)/issues/$($Issue.iid)/related_merge_requests" -Headers $TokenHeader | Where-Object { $_.state -eq "opened" }
)
}
$UserOpenIssues = $UserOpenIssues | Sort-Object -Property #{Expression = { $_.labels[0] } }
Write-Host "Open issues without a merge request assigned to $($User.name):"
$UserOpenIssues
| Where-Object { $_.related_merge_requests.Count -eq 0 }
| Format-Table -Property #(
#{name = "Reference"; expression = { $_.references.full } }
#{name = "Title"; expression = { $_.title } }
#{name = "Labels"; expression = { $_.labels } }
)

How to make Invoke-RestMethod GET and PUT requests to Azure table storage using SAS key

This is a two-part question. I am in the process of automating tasks that a) require information from my Azure table and b) need to update specific entities in my Azure table. I've currently been able to accomplish this by using either of the 2 provided access keys but think this is an unsafe practice and want to define individual policies for different groups and so want to transition into using generated SAS keys.
a) I can currently use SAS policies to retrieve the whole table and find the information I need but I think a better method is to perform an individual query that only pulls the single entity that matches a specific property I'm looking for (e.g. pull all properties of an entity that matches a customer ID: "000000001"). How can I change my code to accomplish this?
$tableName = "accountTD"
$sasReadToken = '<SAS token here>'
$tableUri = "https://$storageAccount.table.core.windows.net/$tableName$sasReadToken"
$GMTTime = (Get-Date).ToUniversalTime().toString('R')
$header = #{
'x-ms-date' = $GMTTime;
Accept = 'application/json;odata=nometadata'
}
$finalResult = Invoke-WebRequest -Uri $tableUri -Headers $header -UseBasicParsing
$finalResult = $finalResult.Content | ConvertFrom-Json
$finalResult.value
b) I also need to update the same entity in the table and can't seem to figure out how to authorize it with my generated SAS key. I'm not sure whether to use Invoke-WebRequest or Invoke-RestMethod or how to go about either of them. Here's what I have so far based on my research.
function addUpdateEntity ($tableName, $PartitionKey, $RowKey, $entity){
$sasReadToken = '<SAS token here>'
$resource = "$tableName(PartitionKey='$PartitionKey',RowKey='$Rowkey')"
$tableUri = "https://$storageAccount.table.core.windows.net/$tableName$sasReadToken"
$GMTTime = (Get-Date).ToUniversalTime().toString('R')
$header = #{
'x-ms-date' = $GMTTime;
Accept = 'application/json;odata=nometadata'
}
$body = $entity | ConvertTo-Json
$item = Invoke-RestMethod -Method PUT -Uri $tableUri -Headers $headers -Body $body -ContentType application/json
}
$mBody = #{
PartitionKey = "MPS02000"
RowKey = "2019-000101"
appUpdateMode = "1"
m_CustID = "000000001"
}
addUpdateEntity -TableName "atdMachines" -PartitionKey $mBody.PartitionKey -RowKey $mBody.RowKey -entity $mBody
Q1. Pull all properties of an entity that matches a customer ID
Answer: You can use $filter query expression. For example, I have 2 entities in my testTable:
I can get the entity whose Id equals to 00001 by making a request as following:
GET https://storagetest789.table.core.windows.net/testTable?{sastoken}&$filter=(Id eq '00001')
$storageAccount = "storagetest789"
$tableName = "testTable"
$sasReadToken = "?sv=2019-02-02&ss=t&sr***************D"
$filter = "`$filter=(Id eq '00001')"
$tableUri = "https://$storageAccount.table.core.windows.net/$tableName$sasReadToken&$filter"
$GMTTime = (Get-Date).ToUniversalTime().toString('R')
$header = #{
'x-ms-date' = $GMTTime;
Accept = 'application/json;odata=nometadata'
}
$finalResult = Invoke-WebRequest -Uri $tableUri -Headers $header -UseBasicParsing
$finalResult = $finalResult.Content | ConvertFrom-Json
$finalResult.value
Result:
Q2. Update the same entity in the table
Answer: Both Invoke-WebRequest and Invoke-RestMethod are suitable for making a HTTP request here. I find some mistakes in your scripts, here is the fixed one:
function addUpdateEntity ($tableName, $PartitionKey, $RowKey, $entity){
$storageAccount = "storagetest789"
$tableName = "testTable"
# Need write access
$sasWriteToken = "?sv=2019-02-02&ss=t&s*****************************D"
$resource = "$tableName(PartitionKey='$PartitionKey',RowKey='$Rowkey')"
# should use $resource, not $tableNmae
$tableUri = "https://$storageAccount.table.core.windows.net/$resource$sasWriteToken"
# should be headers, because you use headers in Invoke-RestMethod
$headers = #{
Accept = 'application/json;odata=nometadata'
}
$body = $entity | ConvertTo-Json
$item = Invoke-RestMethod -Method PUT -Uri $tableUri -Headers $headers -Body $body -ContentType application/json
}
$mBody = #{
PartitionKey = "p1"
RowKey = "r1"
Id = "00001"
Value = "new value"
}
addUpdateEntity -TableName "atdMachines" -PartitionKey $mBody.PartitionKey -RowKey $mBody.RowKey -entity $mBody
Result:

Resources