I have an azure build pipeline task that publishes/creats wiki from a repository. The code is the following
- task: AzurePowerShell@5
inputs:
azureSubscription: '$(service_connection)'
ScriptType: 'InlineScript'
Inline: |
$url = 'https://dev.azure.com/data-platform/uc_test/_apis/wiki/wikis?api-version=6.0'
$body= @'
{
"version": {
"version": "main"
},
"type": "codeWiki",
"name": "wiki",
"projectId": "c800c392-67aa-4892-a070-7284435bda9b",
"repositoryId": "2avd6061-b265-417f-8b55-81cc65kf90b6",
"mappedPath": "/"
}
'@
$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Bearer $(System.AccessToken)"} -Method Post -Body $body -ContentType application/json
echo $response
azurePowerShellVersion: 'LatestVersion'
On the first run of this build pipeline, it successfully publishes/creates wiki. But in the next run, it throws the following error
{"$id":"1","innerException":null,"message":"Wiki already exists with
| name
| 'wiki'.","typeName":"Microsoft.TeamFoundation.Wiki.Server.WikiAlreadyExistsException, Microsoft.TeamFoundation.Wiki.Server","typeKey":"WikiAlreadyExistsException","errorCode":0,"eventId":3000}
How can I tackle this issue? I was thinking if there any way to implement a if else condition under AzurePowerShell@5 task - if wiki doesn't exist- create wiki, else skip the script.
Wiki already exists with
The cause of the issue is that wiki names are unique. When you run successfully for the first time, the wiki name already exists. You need to change the wiki name to let it work again.
I was thinking if there any way to implement a if else condition under AzurePowerShell@5 task - if wiki doesn't exist- create wiki, else skip the script.
Yes. You can use PowerShell script to run the Rest API: Wikis - List to list all wiki names. Then we can check if the wiki name exists and do next actions.
Here is an example:
$Testwikiname = "sampleCodeWiki10"
$url="https://dev.azure.com/orgname/projectname/_apis/wiki/wikis?api-version=7.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$(system.accesstoken)"))
$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json
echo $response
$count = 0
Foreach($wikiname in $response.value.name)
{
echo $wikiname
if($wikiname -eq $Testwikiname)
{
$count = $count + 1
}
}
echo $count
if($count -eq 1 )
{
echo "Wiki Page: $Testwikiname exists in the project"
}
else
{
$url1="https://dev.azure.com/orgname/project/_apis/wiki/wikis?api-version=6.0"
$JSON =
"{
`"version`": {
`"version`": `"master`"
},
`"type`": `"codeWiki`",
`"name`": `"$Testwikiname`",
`"projectId`": `"aaea0fe6-801c-46e3-be1e-dcacdcb0c384`",
`"repositoryId`": `"d7c2d91d-9175-4a45-97bc-aa743275bebc`",
`"mappedPath`": `"/test5`"
}"
$response1 = Invoke-RestMethod -Uri $url1 -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json
echo " Wiki Page: $Testwikiname has been created"
}
Result: