我有一个 PowerShell 脚本,它作为作业的一部分运行 Web 请求。使用作业运行的脚本 block ,我正在记录端点 Uri 和响应时间。然后在所有工作完成之后,但在我删除工作之前,我试图将结果导出到 excel 中。
PS版本:
Major Minor Build Revision
----- ----- ----- --------
5 1 17763 503
代码:
$Code = {
Param(
[array]$Domain,
[array]$Services,
[array]$TestData,
[string]$Path
)
$Log = @()
## Get Random School ##
$Random = Get-Random -InputObject $TestData -Count 1
## Get Random Service ##
$RandService = Get-Random -InputObject $Services
## Get Random Endpoint ##
$ServiceEndpoints = Get-Content "$Path\Service.Endpoints.json" | Out-String | ConvertFrom-Json
$GatewayEndpoints = $ServiceEndpoints.Services.$RandService.Gateway
$RandomEndpoint = Get-Random -InputObject $GatewayEndpoints
$Headers = @{
"Authorization" = "Bearer" + ' ' + $Random.Token
}
$Uri = 'https://' + $Domain + $RandomEndpoint
Try {
$TimeTaken = Measure-Command -Expression {
$JsonResponse = Invoke-WebRequest -Uri $Uri -Headers $Headers -ContentType 'application/json' -Method Get -UseBasicParsing
}
}
Catch {
}
$ResponseTime = [Math]::Round($TimeTaken.TotalMilliseconds, 1)
$LogItem = New-Object PSObject
$LogItem | Add-Member -type NoteProperty -Name 'Endpoint' -Value $Uri
$LogItem | Add-Member -type NoteProperty -Name 'Time' -Value $ResponseTime
$Log += $LogItem
Write-Host $Log
}
#Remove all jobs
Get-Job | Remove-Job
#Start the jobs. Max 4 jobs running simultaneously.
foreach($Row in $TestData){
While ($(Get-Job -state running).count -ge $MaxThreads){
Start-Sleep -Milliseconds 3
}
Start-Job -Scriptblock $Code -ArgumentList $Domain, $Services, $TestData, $Path
}
#Wait for all jobs to finish.
While ($(Get-Job -State Running).count -gt 0) {
start-sleep 1
}
$Log | Export-XLSX -Path .\Test.Results\Performance\Performance.Test.Log.xlsx -ClearSheet
#Get information from each job.
foreach($Job in Get-Job) {
$Info = Receive-Job -Id ($Job.Id)
}
#Remove all jobs created.
Get-Job | Remove-Job
我似乎无法从脚本 block 中获取端点 uri 和响应时间。当我尝试导出
$Log
,所发生的只是它创建了一个空的 excel 文件。写入主机 $Log
@{Endpoint=https://domain/customer/v1/years/2019/marks; Time=1233.3}
@{Endpoint=https://domain/customer/v1/years/2019/marks; Time=2131.7}
最佳答案
您必须返回 $Log
在您的脚本 block 中,因为 $Log
生活在另一个范围内。您可以返回$Log
在您的 $Code
脚本 block ,最后通过 Receive-Job
获取.
将您的代码更改为:
$Code = {
...
$Log += $LogItem
Write-Host $Log
$Log # return via pipeline to the caller
}
正如 Niraj Gajjar 的回答所暗示的,您可以使用
Export-Csv
cmdlet 创建 Excel 文件:#Get information from each job.
foreach($Job in Get-Job) {
Receive-Job -Id ($Job.Id) | Export-CSV -Path .\Test.Results\Performance\Performance.Test.Log.xlsx -Append -NoTypeInformation
}
关于excel - 努力将 PowerShell 作业信息导出到 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56832663/