I am trying run an simple script on Azure VM (Windows) via Invoke-AzureRmVMRunCommand and also via Invoke-RestMethod cmdlet.
Just trying to get the status of DHCP service.
Tried after restarting the VMs
Created a New VM to run the same script but same error
Tried running the invoke command from a different machine
Script stored in a test.ps1 file
Get-Service DHCP
Command:
Invoke-AzureRmVMRunCommand -ResourceGroupName $Resource_Group -VMName $Resource_Name -CommandId RunPowerShellScript -ScriptPath 'C:\Vincent\Azure\AzureVM\Test.ps1'
I even tried using Azure API but same error:
Command:
$Body = #"
{
"commandId": "RunPowerShellScript",
"script": [
"Get-Service DHCP"
]
}
"#
$AppID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$Key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$TenantId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$SubscriptionID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$GetToken = "https://login.microsoftonline.com/$TenantId/oauth2/token?tenant_id=$TenantId"
$Access_Token = Invoke-RestMethod -Method Post -Uri $GetToken -Body "grant_type=client_credentials&client_id=$AppID&client_secret=$Key&resource=$resource"
$Token = $Access_Token.access_token
$API = "https://management.azure.com/subscriptions/$SubscriptionID/resourceGroups/$Resource_Group/providers/Microsoft.Compute/virtualMachines/$VMName/runCommand?api-version=2017-03-30"
Invoke-RestMethod -Method Post -Uri $API -Headers #{Authorization = "Bearer $Token"} -Body $Body -ContentType 'application/json' -OutVariable Result
Error:
Invoke-AzureRmVMRunCommand:
Invoke-AzureRmVMRunCommand : The Resource
'Microsoft.Compute/virtualMachines/XXXXXXXX' under resource
group 'XXXXXX' was not found. ErrorCode: ResourceNotFound
ErrorMessage: The Resource
'Microsoft.Compute/virtualMachines/XXXXXXXX' under resource group
'XXXXXX' was not found. StatusCode: 404 ReasonPhrase: Not Found
OperationID : d5a9e664-92e2-45d6-b5e8-b3d5bd65814c At line:1 char:1
+ Invoke-AzureRmVMRunCommand -ResourceGroupName $Resource_Group -VMName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Invoke-AzureRmVMRunCommand], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Automation.InvokeAzureRmVMRunCommand
Error API:
Invoke-RestMethod : { "error": {
"code": "Conflict",
"message": "Run command extension execution is in progress. Please wait for completion before invoking a run command." } } At line:23
char:1
+ Invoke-RestMethod -Method Post -Uri $API -Headers #{Authorization = " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Invoke-AzureRmVMRunCommand Run command on the VM.
You will receive the error message when you have given wrong “ResourceGroupName”.
You may check the screenshot below: I have provided wrong resource group and changed to correct resource group gives the successful.
In case, if it shows Run command extension execution is in progress, you can check the operation from Azure Portal => Activity log:
You're getting a "resource not found" error:
Error: Invoke-AzureRmVMRunCommand:
Invoke-AzureRmVMRunCommand : The Resource
'Microsoft.Compute/virtualMachines/XXXXXXXX' under resource group
'XXXXXX' was not found. ErrorCode: ResourceNotFound ErrorMessage: The
Resource 'Microsoft.Compute/virtualMachines/XXXXXXXX' under resource
group 'XXXXXX' was not found. StatusCode: 404 ReasonPhrase: Not Found
OperationID : d5a9e664-92e2-45d6-b5e8-b3d5bd65814c At line:1 char:1 +
Invoke-AzureRmVMRunCommand -ResourceGroupName $Resource_Group -VMName
... +
+ CategoryInfo : CloseError: (:) [Invoke-AzureRmVMRunCommand], ComputeCloudException + FullyQualifiedErrorId :
Microsoft.Azure.Commands.Compute.Automation.InvokeAzureRmVMRunCommand
And then you're getting an error saying "You're running invoke-azurermvmruncommand", wait till that's completed:
Error API:
Invoke-RestMethod : { "error": { "code": "Conflict", "message": "Run
command extension execution is in progress. Please wait for completion
before invoking a run command." } } At line:23 char:1 +
Invoke-RestMethod -Method Post -Uri $API -Headers #{Authorization = "
... +
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException + FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
run this to check if the VM is where it's supposed to be, and then your script:
get-azurermvm -resourcegroupname $Resource_Group -Name $Resource_Name
$file = "C:\Vincent\Azure\AzureVM\Test.ps1"
Invoke-AzureRmVMRunCommand -ResourceGroupName $Resource_Group -VMName $Resource_Name -CommandId RunPowerShellScript -ScriptPath $file
If that still doesn't work, please share with us $Resource_Name.GetType() and $Resource_Group.GetType()
You need to call Set-AzureRmContext before calling Invoke-AzureRmVMRunCommand, by setting the -SubscriptionName from the Virtual Machine's Subscription.
Related
I'm trying integrating-teamcity-with-msteams by execute below powershell script from one of the Build Step in Teamcity to hit the Microsoft teams. When I executed the same powershell script from "Postman" its working fine and from teamcity its failing and suggestions to fix the issue.
$body = #{
title= "Message Title";
text= "Message content"
} | ConvertTo-Json -Depth 4
Invoke-WebRequest -Method Post -Uri "http://shiftup.webhook.office.com/webhookb2/b7f49321-8fdb-4a74-8f86-ef7cd7cffe52#d852d5cd-724c-4128-8812-ffa5db3f8507/IncomingWebhook/8f72d2f94a4c4691b303c53be43fa462/f83d02ad-eb2a-4054-8b49-0ec780812870" -Body $body -ContentType "application/json" -UseBasicParsing
Teamcity Error:
Step 1/1: Send Teams Nofitication (PowerShell)
15:02:56 PowerShell Executable: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
15:02:56 Working directory: G:\CIQ00\data\agent02\work\bacf322751a460f
15:02:56 Command: C:\Windows\sysnative\WindowsPowerShell\v1.0\powershell.exe
15:02:56 PowerShell arguments: -NoProfile, -NonInteractive, -ExecutionPolicy, ByPass, -File, G:\CIQ00\data\agent02\temp\buildTmp\powershell7256209341500178754.ps1
15:02:56 Invoke-WebRequest : The remote name could not be resolved: 'shiftup.webhook.office.com'
15:02:56 At G:\CIQ00\data\agent02\temp\buildTmp\powershell7256209341500178754.ps1:5 char:1
15:02:56 + Invoke-WebRequest -Method Post -Uri https://shiftup.webhook.office.co ...
15:02:56 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15:02:56 + CategoryInfo : NotSpecified: (:) [Invoke-WebRequest], WebException
15:02:56 + FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Invoke-WebRequest : The remote name could not be resolved: 'shiftup.webhook.office.com'
I have been working with Powershell all day, playing with proxy settings and related. A POST request that once worked earlier in the day, is now stating a very bizarre error:
The request:
$tenantId = '8331e1..........'
$client_id = 'a3b869ef................
$client_secret = '0w;m$................'
#************ GET AAD TOKEN ************
$url = "https://login.microsoftonline.com/" + $tenantId + "/oauth2/token"
$body = #{
grant_type = 'client_credentials'
client_id = $client_id
client_secret = $client_secret
resource = 'https://dev.azuresynapse.net'
}
$GetAADResult = Invoke-WebRequest -Method 'Post' -Uri $url -Body $body
$GetAAD_Content_JSON = $GetAADResult.Content | ConvertFrom-Json
$access_token = $GetAAD_Content_JSON.access_token
# print access_token
$access_token
This used to provide a simple token as a response, but now it is returning the error:
Invoke-WebRequest : The remote name could not be resolved: 'http'
At line:24 char:17
+ ... GetAADResult = Invoke-WebRequest -Method 'Post' -Uri $url -Body $body
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:26 char:48
+ $GetAAD_Content_JSON = $GetAADResult.Content | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
I do not know what needs to change to get this functionating again, it appears PowerShell is looking for a proxy setting in every request...? Anny ideas?
I ended up undoing these steps: https://spaghettidba.com/2017/12/19/recovering-the-psgallery-repository-behind-a-corporate-proxy/
I am running into an strange issue building a Powershell script. I want to programatically connecto to Microsoft Teams and execute some skype for businesss online commands.
When I simply do on a terminal
Connect-MicrosoftTeam and get prompted and import my credentials, it all works perfectly, but i need to this programatically.
I did an app registration with the following permissions
And I am authenticating against Azure AD and Graph:
#Connect to Graph
$Body = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $ApplicationID
Client_Secret = $AccessSecret
}
$ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenatDomainName/oauth2/v2.0/token" -Method POST -Body $Body
$token = $ConnectGraph.access_token
#Connect to AD
$uri = "https://login.microsoftonline.com/${tenant_id}/oauth2/token"
$body = #{grant_type='refresh_token';resource='https://graph.windows.net';client_id=$clientId;refresh_token=$refresh_token}
$result = Invoke-RestMethod -Method Post -Uri $uri -Body $body
$accessToken = $result.access_token
Then I run
Connect-MicrosoftTeams -AadAccessToken $accessToken -MsAccessToken $token -AccountId $account
And it doesn't throw an error, works properly. and i gen run commands like Get-Team and returns the info correctly. However when I try to run an skype command like
Get-CsOnlineVoiceUser
I get the error
Get-CsOnlineSession : Run Connect-MicrosoftTeams before running cmdlets.
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:63 char:22
+ $remoteSession = & (Get-CsOnlineSessionCommand)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-CsOnlineSession], UnauthorizedAccessException
+ FullyQualifiedErrorId : UnauthorizedAccessException,Microsoft.Teams.ConfigApi.Cmdlets.GetCsOnlineSession
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:10006 char:38
+ ... -Session (Get-PSImplicitRemotingSession -CommandName 'Get-CsOnline ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
Am I missing something? I am using the 2.3.1 Teams Module.
Thanks!
This is a bit tricky to do, but can be achieved.
I recommend reading this blog post for exact instructions and code examples:
https://paulobrien.co.nz/2020/06/29/s4b-online-powershell-modern-auth/
Should get you started.
I want to use PowerShell to set shareddataset for a report using SSRS API.
I have already tried to use PowerShell to get shareddataset using SSRS API successfully. But failed to use put method.
Success using get method:
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/DataSets"
`
`$Body = #{
Path ="/Shared_data_sets/P_Calculate_date_Default_key";
output_mode = "csv";
earliest_time = "-2d#d";
latest_time = "-1d#d";
}
Invoke-RestMethod -Method 'GET' -Uri $url -Credential $Cred -Body $body -OutFile output.csv
failed using put method:
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6";
Name = "P_Calculate_Date_Default_Key";
Path = "/Shared_data_sets/P_Calculate_date_Default_key";
Type = "DataSet" ;
}
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method 'PUT'
Error returned is
The remote server returned an error: (400) Bad Request
detailed error:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request. At line:12 char:1 + Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method 'PU ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I hope the put method could be working. I thought I was using the same way as the get method but it still failed.
I tried another way but still failed :
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6"
Name = "P_Calculate_Date_Default_Key"
Path = "/Shared_data_sets/P_Calculate_date_Default_key"
Type = "DataSet"
}| ConvertTo-Json
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT -ContentType "application/json" | Out-Null
Just for you to know that for the put method, i have already tested on postman and it works. So I guess currently it is only due to some logic in powershell side inconsistent.
in postman I put the link as :
http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets
Body as :
[
{
"Id": "935be257-5a65-4c0d-b372-d5a6a188daf6",
"Name": "P_Calculate_Date_Default_Key",
"Path": "/Shared_data_sets/P_Calculate_date_Default_key",
"Type": "DataSet"
}
]
I tried your recommendation and it shows below , I have added it below all:
PS C:\Users\dkx42a8adm> $Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6"
Name = "P_Calculate_Date_Default_Key"
Path = "/Shared_data_sets/P_Calculate_date_Default_key"
Type = "DataSet"
}| ConvertTo-Json
Write-Output $Body
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT -ContentType "application/json"
$error[0]|format-list -force
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
{
"Path": "/Shared_data_sets/P_Calculate_date_Default_key",
"Name": "P_Calculate_Date_Default_Key",
"Id": "935be257-5a65-4c0d-b372-d5a6a188daf6",
"Type": "DataSet"
}
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:14 char:1
+ Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Exception : System.Net.WebException: The remote server returned an error: (400) Bad Request.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
TargetObject : System.Net.HttpWebRequest
CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at , : line 14
PipelineIterationInfo : {}
PSMessageDetails :
I'm trying to convert this working request done in Cygwin to Powershell:
Cygwin (Working):
curl -k -u curl:Password -X PUT -F "file=$($_)" https://$($appliance)/wse/customblockpage/file/en
Powershell (not working):
Invoke-Webrequest -Uri "https://$($appliance)/wse/customblockpage/file/en" -Method Put -Infile "$homePath\$($_)" -Credential $cred
Here is the error I get:
Invoke-Webrequest : { "Error": "No file part in file", "Result": "Failure" }
At line:1 char:1
+ Invoke-Webrequest https://{IP Address Masked}/wse/customblockpage/file/en ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The { "Error": "No file part in file", "Result": "Failure" } is actually the error response from the web server and not a specific PowerShell error message.
In your cURL invocation, you are specifying form data with the -F flag, yet you don't appear to be doing the same in PowerShell.
In PowerShell, you can specify form data using the -Body flag like this:
Invoke-Webrequest -Uri "https://example.com/" -Method Put -Body #{ "file" = "hello.txt" }
If you need to send the actual content of the file, then you can use this as your -Body argument:
-Body #{ "file" = (Get-Content hello.txt) }