-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathInitialize-LPMSLogAnalyticsApi.ps1
More file actions
371 lines (305 loc) · 13.5 KB
/
Initialize-LPMSLogAnalyticsApi.ps1
File metadata and controls
371 lines (305 loc) · 13.5 KB
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
function Initialize-LPMSLogAnalyticsApi {
<#
.SYNOPSIS
Initializes and registers the Log Analytics API service for use with Entra authentication.
.DESCRIPTION
This function registers the Azure Log Analytics API service with the Entra service registry,
enabling authenticated queries against Log Analytics workspaces using the api.loganalytics.azure.com
endpoint. It is required before making any Log Analytics queries via Invoke-EntraRequest.
The function performs the following operations:
1. Checks if the LogAnalytics service is already registered
2. If not registered, configures the service with appropriate endpoints and settings
3. Registers the service with Register-EntraService
4. Returns status information about the registration
Service Configuration:
The registration includes:
- **Service Name**: "LogAnalytics"
- **API Endpoint**: https://api.loganalytics.azure.com
- **OAuth Resource**: https://api.loganalytics.io (for token acquisition)
- **Default Headers**: Content-Type: application/json
- **Token Refresh**: Enabled (automatic token renewal)
- **Help URL**: Microsoft documentation link
Key Features:
- **Idempotent**: Safe to call multiple times (checks before registering)
- **Session Scope**: Registration persists for PowerShell session lifetime
- **Error Tolerant**: Returns clear status instead of failing on re-registration
- **Verbose Logging**: Detailed status messages for troubleshooting
This is a **one-time setup per PowerShell session**, though it's safe to call multiple times
as it checks for existing registration before attempting to register again.
Use Cases:
- **Module Initialization**: Setup before querying Log Analytics
- **Script Automation**: Ensure service is registered in automated workflows
- **Multi-Service Scripts**: Register alongside Graph API services
- **Troubleshooting**: Verify service registration status
.PARAMETER None
This function does not accept any parameters.
.OUTPUTS
PSCustomObject
Returns an object with the following properties:
PSTypeName (String)
Type name for PowerShell formatting system
Value: "Entra.ServiceRegistration"
ServiceName (String)
The name of the registered service
Value: "LogAnalytics"
AlreadyRegistered (Boolean)
Indicates if service was previously registered
- True: Service existed before this call
- False: Service was newly registered by this call
Status (String)
Human-readable registration status
Values:
- "AlreadyRegistered": Service was already configured
- "NewlyRegistered": Service was registered by this call
.EXAMPLE
Initialize-LPMSLogAnalyticsApi
ServiceName : LogAnalytics
AlreadyRegistered : False
Status : NewlyRegistered
Description:
Registers the Log Analytics API service for the first time in the session.
The service is now ready for authentication and queries.
.EXAMPLE
$result = Initialize-LPMSLogAnalyticsApi
if ($result.Status -eq 'NewlyRegistered') {
"Log Analytics API is now ready for use"
} else {
"Log Analytics API was already initialized"
}
Description:
Captures the registration result and provides feedback based on whether
the service was newly registered or already available.
.EXAMPLE
# Complete authentication workflow
Initialize-LPMSLogAnalyticsApi
Connect-EntraService -ClientID $clientId -TenantID $tenantId -ClientSecret $secret -Service 'LogAnalytics'
$workspaceId = "12345678-1234-1234-1234-123456789012"
$query = "MicrosoftGraphActivityLogs | where TimeGenerated > ago(7d) | take 10"
$result = Invoke-EntraRequest -Service 'LogAnalytics' -ApiUrl "/v1/workspaces/$workspaceId/query" -Method POST -Body @{query = $query}
Description:
Complete workflow showing initialization, authentication, and querying Log Analytics.
This is the typical pattern for using the module with Log Analytics.
.EXAMPLE
Initialize-LPMSLogAnalyticsApi -Verbose
VERBOSE: LogAnalytics service was already registered. Skipping initialization.
ServiceName : LogAnalytics
AlreadyRegistered : True
Status : AlreadyRegistered
Description:
Runs with verbose output showing the service was already configured.
Useful for troubleshooting and understanding script behavior.
.EXAMPLE
# Register multiple services in a script
Initialize-LPMSLogAnalyticsApi | Out-Null
Connect-EntraService -Service 'GraphBeta'
Connect-EntraService -Service 'LogAnalytics' -ClientID $clientId -TenantID $tenantId -ClientSecret $secret
$apps = Get-LPMSAppRoleAssignment
$appsWithActivity = $apps | Get-LPMSAppActivityData -WorkspaceId $workspaceId -Days 30
$analysis = $appsWithActivity | Get-LPMSPermissionAnalysis
Description:
Shows how to initialize Log Analytics alongside Graph API services for complete
permission analysis workflows. Output is suppressed with Out-Null since we only
care about the side effect (registration).
.EXAMPLE
# Verify service registration status
Initialize-LPMSLogAnalyticsApi
$service = Get-EntraService -Name 'LogAnalytics'
if ($service) {
"Service URL: $($service.ServiceUrl)"
"OAuth Resource: $($service.Resource)"
"Status: Ready for authentication"
}
Description:
Initializes the service and then verifies its configuration by retrieving
the registered service details.
.EXAMPLE
# Error handling in automation
try {
$init = Initialize-LPMSLogAnalyticsApi -ErrorAction Stop
"Initialization $($init.Status): $($init.ServiceName)"
Connect-EntraService -Service 'LogAnalytics' -ClientID $clientId -TenantID $tenantId -ClientSecret $secret -ErrorAction Stop
"Authentication successful"
}
catch {
Write-Error "Failed to setup Log Analytics API: $_"
exit 1
}
Description:
Demonstrates proper error handling for automated scripts and CI/CD pipelines.
Uses -ErrorAction Stop to ensure failures are caught and handled appropriately.
.NOTES
Prerequisites:
- EntraService module must be loaded and available
- Register-EntraService and Get-EntraService cmdlets must be present
- Must be called before any Log Analytics API operations
- No Azure authentication required for initialization (only registration)
Service Configuration Details:
The function registers the following configuration:
Service URL: https://api.loganalytics.azure.com
- Primary API endpoint for Log Analytics queries
- Used for all workspace query operations
OAuth Resource: https://api.loganalytics.io
- Azure AD resource identifier for token acquisition
- Required for obtaining access tokens
Default Headers:
- Content-Type: application/json (required for query API)
Token Management:
- Token refresh enabled (NoRefresh = $false)
- Automatic token renewal before expiration
- No manual token management required
Idempotency and Safety:
- Function is **idempotent** - safe to call multiple times
- Checks for existing registration before proceeding
- Returns status indicating whether registration was performed
- No side effects if service already registered
- Does not re-register or overwrite existing configuration
Session Scope and Persistence:
- Registration persists for the **current PowerShell session only**
- Must be re-initialized in new PowerShell sessions
- Does not persist across PowerShell restarts
- Not stored in profile or registry
- Each script/session must call initialization
Error Handling:
- Uses -ErrorAction SilentlyContinue when checking existing registration
- Returns cleanly if service already registered (no error)
- Throws detailed error if registration fails
- Uses Write-Error for registration failures
- Error messages include full exception details
Logging Levels:
- **Write-PSFMessage -Level Debug -Message**: Detailed processing steps (use -Debug switch)
* Service registration check
* Registration success confirmation
* Status determination
- **Write-PSFMessage -Level Verbose -Message "Your message here"**: Key status messages (use -Verbose switch)
* Already registered notification
* New registration notification
- **Write-Error**: Registration failures
* Exception details
* Full error context
Return Object:
The returned PSCustomObject includes:
- **PSTypeName**: Enables custom formatting if defined
- **ServiceName**: Always "LogAnalytics" for consistency
- **AlreadyRegistered**: Boolean for conditional logic
- **Status**: Human-readable string for display
Common Patterns:
Silent initialization (most common):
```powershell
Initialize-LPMSLogAnalyticsApi | Out-Null
```
Conditional logic based on status:
```powershell
$result = Initialize-LPMSLogAnalyticsApi
if (-not $result.AlreadyRegistered) {
"Service newly registered - first use in this session"
}
```
Error handling in production:
```powershell
try {
Initialize-LPMSLogAnalyticsApi -ErrorAction Stop
} catch {
Write-Error "Failed to initialize Log Analytics API: $_"
exit 1
}
```
Troubleshooting:
If "Register-EntraService not found" error:
- Ensure EntraService module is loaded: Import-Module EntraService
- Check module availability: Get-Module EntraService -ListAvailable
- Verify correct module version installed
If registration fails:
- Check error message for specific failure reason
- Verify no conflicting service registration exists
- Try restarting PowerShell session
- Ensure module dependencies are met
If Get-EntraService fails during initialization:
- This is expected behavior (uses SilentlyContinue)
- Function handles this gracefully
- Only causes issue if Get-EntraService is missing entirely
Integration with Other Commands:
This function is typically used in conjunction with:
- Connect-EntraService: Authenticate to Log Analytics
- Invoke-EntraRequest: Execute Log Analytics queries
- Get-LPMSAppActivityData: Retrieve application activity from logs
- Get-LPMSAppThrottlingData: Get throttling statistics from logs
Best Practices:
- Call at the beginning of scripts that use Log Analytics
- Include in module initialization code
- Use Out-Null if you don't need the return value
- Always call before Connect-EntraService for Log Analytics
- Include error handling in production automation
- Use -Verbose during development and troubleshooting
Performance:
- Initialization is very fast (< 100ms)
- No network calls made during registration
- Negligible memory footprint
- No impact on subsequent API calls
Related Cmdlets:
- Register-EntraService: Underlying registration function
- Get-EntraService: Retrieve registered service configuration
- Connect-EntraService: Authenticate to registered services
- Invoke-EntraRequest: Make API calls to registered services
.LINK
https://docs.microsoft.com/en-us/azure/azure-monitor/logs/api/overview
.LINK
https://mynster9361.github.io/Least_Privileged_MSGraph/commands/Initialize-LPMSLogAnalyticsApi.html
#>
[CmdletBinding()]
[OutputType([PSCustomObject])]
param ()
begin {
Write-PSFMessage -Level Debug -Message "Checking if LogAnalytics service is already registered..."
$verifyRegistration = Get-EntraService -Name 'LogAnalytics' -ErrorAction SilentlyContinue
if ($null -ne $verifyRegistration) {
Write-PSFMessage -Level Debug -Message "LogAnalytics service is already registered."
$alreadyRegistered = $true
}
else {
$alreadyRegistered = $false
}
}
process {
# Skip registration if already registered
if ($alreadyRegistered) {
Write-PSFMessage -Level Verbose -Message "LogAnalytics service was already registered. Skipping initialization."
return
}
Write-PSFMessage -Level Verbose -Message "Registering LogAnalytics service..."
$LogAnalyticsCfg = @{
Name = 'LogAnalytics'
ServiceUrl = 'https://api.loganalytics.azure.com'
Resource = 'https://api.loganalytics.io'
DefaultScopes = @()
HelpUrl = 'https://docs.microsoft.com/en-us/azure/azure-monitor/logs/api/overview'
Header = @{
'Content-Type' = 'application/json'
}
NoRefresh = $false
}
try {
Register-EntraService @LogAnalyticsCfg
Write-PSFMessage -Level Debug -Message "LogAnalytics service registered successfully."
}
catch {
Write-Error "Failed to register LogAnalytics service: $_"
throw
}
}
end {
$statusMessage = if ($alreadyRegistered) {
"AlreadyRegistered"
}
else {
"NewlyRegistered"
}
Write-PSFMessage -Level Debug -Message "LogAnalytics service initialization completed. Status: $statusMessage"
# Return structured object with clear status
return [PSCustomObject]@{
PSTypeName = 'Entra.ServiceRegistration'
ServiceName = 'LogAnalytics'
AlreadyRegistered = $alreadyRegistered
Status = $statusMessage
}
}
}