Posted on 1 Comment

Install Azure DevOps agent using powershell

With Azure devops you can create incredible automations. But in many cases you will need first to install the azure devops agent in order to run your tasks. Using the below powershell you can automate the installation of an azure devops agent.

New-Item "C:\agent" -itemType Directory
cd "C:\agent"
$url = "https://dev.azure.com/YOUR_ORG"
$token = "PAT_TOKEN"
$auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$token"))

$package = Invoke-RestMethod "$url/_apis/distributedtask/packages/agent?platform=win-x64&$`top=1" -Headers @{Authorization = "Basic $auth"}

$fileName = $package.value[0].fileName;
$downloadUrl = $package.value[0].downloadUrl;
    

Invoke-WebRequest -UseBasicParsing $downloadUrl -OutFile agent.zip
Expand-Archive -Force agent.zip -DestinationPath .
Remove-Item -Force agent.zip


.\config.cmd --unattended --replace --acceptTeeEula --work work --url https://dev.azure.com/YOUR_ORG --pool YOUR_POOL_NAME --auth pat --token $token --runAsService --runAsAutoLogon --windowsLogonAccount USER --windowsLogonPassword USER_PASSWORD
.\run.cmd

During the installation you may notice a problem for the powershell task to write on the log file.

Nevertheless the agent will be installed successfully.

Posted on Leave a comment

Restore transaction log backup on MS SQL server using powershell

Recently working on a pipeline, I wanted to restore multiple transaction log backups on a MS SQL server. The files were located under R:\files\incremental.

You can use below powershell in order to do the restore automatically.

$folder_for_cleanup = "R:\files\incremental"
Get-ChildItem $folder_for_cleanup | Sort -Property FullName | ForEach-Object {
Write-Host restoring $_.FullName
sqlcmd -Q "RESTORE LOG [Database_Name] FROM DISK=N'$_' WITH NORECOVERY" -o R:\files\results\incrementalresult.txt; #writing a log output
[string]$result = Get-Content R:\files\results\incrementalresult.txt
if ($result.contains('terminates')) {
Write-Host backup is already present in the database, skipping …
Remove-Item $_.FullName -Force -Confirm:$false
}
else {
Write-Host sucessfully restored $_.FullName
Remove-Item $_.FullName -Force -Confirm:$false
}
}

The above powershell will try to restore the X transaction log in the database. If the one is already restored, it will skip, else the log will be restored.

Posted on Leave a comment

Authentication failed. The ‘Authorization’ header is missing – Invoke-WebRequest Azure ARM

While building an automation procedure I had to POST the management API of Azure.

Invoke-WebRequest -Uri https://management.azure.com/subscriptions/pool/xxx/xxxx/xxxx/xxxx -Method POST

When I used the Invoke-WebRequest without Authentication it failed. The error that you will get when you do not have Authentication headers set can be found below.

Invoke-WebRequest: {"error":{"code":"AuthenticationFailed","message":"Authentication failed. The 'Authorization' header is missing."}}

In order to authenticate with azure you can get an access-token using az cli.

az account get-access-token

The output will look like the below output:

{
  "accessToken": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxVG-hTDHECYJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-B5FA9l9RvqOls3iaDDYw5O86acvLIwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-ixxxxxxxxxxxxxxxxx3eoeKlxZfxxxxxxxxxxfGW2O6oA",
  "expiresOn": "2022-05-05 14:51:08.000000",
  "subscription": "a23eef11-f200-4722-866c-248ca45142f6",
  "tenant": "1efa646f-3fc3-4554-bd8c-651879a2b110",
  "tokenType": "Bearer"
}

You should take the output of the token and use it on your call.

For example using POSTMAN you should place your token under the Authorization tab. You will then be able to get the result from Azure ARM api.

Posted on 2 Comments

InvalidAuthenticationToken “message”:”The access token is invalid.” – Powershell

The below sample code will make an HTTP call using powershell with Authorization headers. However when you run the code it will fail.

$token =  az account get-access-token | ConvertFrom-Json
$mytoken =  $token.accesstoken
$headers = @{ Authorization = "Bearer $token.accesstoken" }
echo $headers
Invoke-RestMethod -Method Get -Uri "https://management.azure.com/subscriptions/xxxxx/resourceGroups/resource-group/providers/Microsoft.Sql/servers/sql-server?api-version=2020-11-01-preview" -Headers $headers -UseBasicParsing

This is an error occuring on powershell as the $token.accesstoken is not correctly parsed. In order to resolve either use a new variable and assign the value on it ($mytoken)

$headers = @{ Authorization = "Bearer $mytoken" }