-
Notifications
You must be signed in to change notification settings - Fork 6
/
upload_signals.ps1
156 lines (136 loc) · 4.51 KB
/
upload_signals.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
param
(
[Parameter(mandatory = $true)]
[string] $tenantId,
[Parameter(mandatory = $true)]
[string] $appId,
[Parameter(mandatory = $true)]
[string] $appSecret,
[Parameter(mandatory = $true)]
[string] $jobId,
[Parameter(mandatory = $true)]
[string] $csvFilePath
)
# Access Token Config
$oAuthTokenEndpoint = "https://login.windows.net/$tenantId/oauth2/token"
$resource = 'https://microsoft.onmicrosoft.com/4e476d41-2395-42be-89ff-34cb9186a1ac'
# Csv upload config
$eventApiURl = "https://webhook.ingestion.office.com"
$eventApiEndpoint = "api/signals"
function GetAccessToken () {
# Token Authorization URI
$uri = "$($oAuthTokenEndpoint)?api-version=1.0"
# Access Token Body
$formData =
@{
client_id = $appId;
client_secret = $appSecret;
grant_type = 'client_credentials';
resource = $resource;
tenant_id = $tenantId;
}
# Parameters for Access Token call
$params =
@{
URI = $uri
Method = 'Post'
ContentType = 'application/x-www-form-urlencoded'
Body = $formData
}
$response = Invoke-RestMethod @params -ErrorAction Stop
return $response.access_token
}
function RetryCommand {
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $true)]
[scriptblock]$ScriptBlock,
[Parameter(Position = 1, Mandatory = $false)]
[int]$Maximum = 15
)
Begin {
$cnt = 0
}
Process {
do {
$cnt++
try {
$ScriptBlock.Invoke()
return
}
catch {
Write-Error $_.Exception.InnerException.Message -ErrorAction Continue
Start-Sleep 60
if ($cnt -lt $Maximum) {
Write-Output "Retrying"
}
}
} while ($cnt -lt $Maximum)
throw 'Execution failed.'
}
}
function WriteErrorMessage($errorMessage) {
$Exception = [Exception]::new($errorMessage)
$ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
$Exception,
"errorID",
[System.Management.Automation.ErrorCategory]::NotSpecified,
$TargetObject
)
$PSCmdlet.WriteError($ErrorRecord)
}
function UploadCsvData ($access_token) {
$nvCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
$nvCollection.Add('jobid', $jobId)
$uriRequest = [System.UriBuilder]"$eventApiURl/$eventApiEndpoint"
$uriRequest.Query = $nvCollection.ToString()
$fieldName = 'file'
$url = $uriRequest.Uri.OriginalString
Add-Type -AssemblyName 'System.Net.Http'
$client = New-Object System.Net.Http.HttpClient
$content = New-Object System.Net.Http.MultipartFormDataContent
try{
$fileStream = [System.IO.File]::OpenRead($csvFilePath)
$fileName = [System.IO.Path]::GetFileName($csvFilePath)
$fileContent = New-Object System.Net.Http.StreamContent($fileStream)
$content.Add($fileContent, $fieldName, $fileName)
}catch [System.IO.FileNotFoundException]{
Write-Error("Csv file not found. ")
return
}catch [System.IO.IOException]{
Write-Error("Csv file might be open")
return
}catch {
Write-Error("Error reading from csv file")
return
}
$client.DefaultRequestHeaders.Add("Authorization", "Bearer $access_token");
$client.Timeout = New-Object System.TimeSpan(0, 0, 400)
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$result = $client.PostAsync($url, $content).Result
}
catch {
WriteErrorMessage("Unknown failure while uploading.")
return
}
$status_code = [int]$result.StatusCode
if ($result.IsSuccessStatusCode) {
Write-Output "Upload Successful"
$responseStr = $result.Content.ReadAsStringAsync().Result
if (! [string]::IsNullOrWhiteSpace($responseStr)) {
Write-Output("Body : {0}" -f $responseStr)
}
}
elseif ($status_code -eq 0 -or $status_code -eq 501 -or $status_code -eq 503) {
throw "Service unavailable."
}
else {
WriteErrorMessage("Failure with StatusCode [{0}] and ReasonPhrase [{1}]" -f $result.StatusCode, $result.ReasonPhrase)
WriteErrorMessage("Error body : {0}" -f $result.Content.ReadAsStringAsync().Result)
}
}
RetryCommand -ScriptBlock {
$access_token = GetAccessToken
UploadCsvData($access_token)
}