【发布时间】:2018-12-06 17:53:34
【问题描述】:
我认为我发现 PowerShell 脚本无法解释。下面我来描述一下这个问题:
我创建了一个函数,它将查询 VSTS 并输出包含特定标签的错误数量。
function GetBugsFromVSTS($applicationName, $first_url, $second_url, $query) {
#Building the body of the HTTP request to VSTS endpoint
$bodyOfRequest = $query | ConvertTo-Json
#Building headers of the HTTP request to VSTS endpoint
$headers = @{
'Content-Type'='application/json'
'Accept'='application/json'
'Authorization' = '' + $vsts_access_token + ''
}
$getBugs = Invoke-RestMethod -Uri $first_url `
-Method Post `
-Body $bodyOfRequest `
-Headers $headers | ConvertTo-Json -Depth 100
$json_decoded = $getBugs | ConvertFrom-Json
if ($json_decoded.workItems -eq $null) {
Write-Host "$applicationName Json decoded workitems are equal null" -ForegroundColor Red
} else {
Write-Host "$applicationName Json decoded workitems are not null" -ForegroundColor Green
$json_decoded.workItems | % {
$bug_id = $_.id
Write-Host $bug_id
}
}
$json_decoded.workItems | % {
$bug_id = $_.id
$url = ($second_url +$bug_id)
$getVstsBugState = Invoke-RestMethod -Uri $url -Method Get -Headers $headers
[PSCustomObject]@{
"Application Name" = $applicationName
"Id" = $bug_id;
"State" = $getVstsBugState.fields.'System.State';
"Reason" = $getVstsBugState.fields.'System.Reason';
"Severity" = $getVstsBugState.fields.'Microsoft.VSTS.Common.Severity'.Substring(4);
"AssignedTo" = $getVstsBugState.fields.'System.AssignedTo'.displayName
}
}
}
当我尝试运行它时
$application = "MyBeautifulApp"
$application_first_url = "https://test.visualstudio.com/72L80E4b-1583-45c1-b669-d8de6133V895/_apis/wit/wiql?api-version=1.0"
$application_second_url = "https://test.visualstudio.com/72L80E4b-1583-45c1-b669-d8de6133V895/_apis/wit/workItems/"
$application_query = @{"query" = "SELECT [System.Id],[System.WorkItemType],[System.Title],[System.AssignedTo],[System.State] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.WorkItemType] = 'Bug' AND [System.Title] CONTAINS 'Test' AND [System.TAGS] CONTAINS 'Test'"}
GetBugsFromVSTS $application $application_first_url $application_second_url $application_query
} catch {
Write-Warning "##vso[task.logissue type=warning;]Some problem occured querying MyBeautifulApp application. Please see below for error details"
$_
}
这里最有趣的部分是我收到了这个非常奇怪的错误消息
警告:##vso[task.logissue type=warning;]发生了一些问题 查询 MyBeautifulApp 应用程序。请参阅下面的错误 详情
% : 不能在空值表达式上调用方法。
为了测试,我添加了if..else 子句来测试$json_decoded.workItems 不等于null,并且验证通过。如果我运行代码,完整的输出将是
$json_decoded.workItems 的第一次验证(第 23 行)怎么可能没有表明变量等于 null,而第二个语句(第 29 行)显示它是空的吗?
【问题讨论】:
-
该错误似乎与
ForEach-Object部分有关。您是否调查过$getVstsBugState以确保它也不为空并且包含您要索引的属性?field.'System.State等
标签: powershell null