├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── Add-GroupMemberByCompliance └── Add-GroupMemberByCompliance.ps1 ├── AzFunctionMultiTenantWI-Demo ├── .funcignore ├── .gitignore ├── .vscode │ ├── extensions.json │ ├── launch.json │ ├── settings.json │ └── tasks.json ├── GetDevicesAzPwsh │ ├── function.json │ ├── run.ps1 │ └── sample.dat ├── GetDevicesDemoPwsh │ ├── function.json │ ├── run.ps1 │ └── sample.dat ├── host.json ├── profile.ps1 └── requirements.psd1 ├── AzTableAPIExamples └── AzTableAPIExample.ps1 ├── AzureVPNAutoConnect └── Deploy-AzureVPNWithAutoConnect.ps1 ├── CertificateExpiration └── Get-CertificateExpiry.ps1 ├── DemoModule ├── .gitignore ├── DemoModule │ ├── DemoModule.psd1 │ ├── DemoModule.psm1 │ ├── Private │ │ ├── .gitkeep │ │ └── Get-RandomPlanet.ps1 │ ├── Public │ │ ├── .gitkeep │ │ ├── Invoke-PlanetGreeting.ps1 │ │ └── Test-OddOrEven.ps1 │ ├── ReleaseNotes.txt │ └── description.txt ├── README.md └── build.ps1 ├── Dynamic-Group-Automation ├── .funcignore ├── .gitignore ├── .vscode │ ├── extensions.json │ ├── launch.json │ ├── settings.json │ └── tasks.json ├── Dynamic-Group-Function │ ├── function.json │ ├── run.ps1 │ └── sample.dat ├── host.json ├── profile.ps1 ├── proxies.json └── requirements.psd1 ├── Expand-Intunewin ├── Decrypt-IntuneFromLogs.ps1 ├── DecryptAndExpandFromLogs.ps1 ├── Expand-IntunewinFromFile.ps1 ├── Expand-IntunewinFromLogs.ps1 └── readme.md ├── FIleHashValidation ├── Get-ComputedMD5.ps1 ├── Get-RemoteFIleIfHashIsKnown.ps1 └── Get-RemoteFileAndConfirmHashValidationLocally.ps1 ├── Get-TenantIdFromDomain └── Get-TenantIdFromDomain.ps1 ├── Get-Win32AppsUsingMSAL └── Get-Win32AppsUsingMSAL.ps1 ├── GetMeABeer.ps1 ├── GraphApiToMSI └── Add-GraphApiRoleToMSI.ps1 ├── Import-VSCodeThemeToTerminal └── Import-VSCodeThemeToTerminal.ps1 ├── Install-Fonts └── Install-Fonts.ps1 ├── Install-MicrosoftTeams ├── Install-MicrosoftTeams.ps1 └── readme.md ├── Install-Printers ├── Configure-Policies.ps1 └── Install-Printers.ps1 ├── IntuneMonitoring ├── IntuneConfigMonitoring │ ├── IntuneConfigMonitoring.ps1 │ └── appConfig.json ├── IntuneConfigSnapshot │ ├── IntuneConfigSnapshot.ps1 │ └── appConfig.json └── readme.md ├── Invoke-GraphConnector ├── Invoke-GraphConnector.ps1 ├── Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll ├── Microsoft.IdentityModel.Clients.ActiveDirectory.dll ├── appConfig.json └── readme.md ├── LICENSE ├── MSI-AzFunction-Demo ├── .funcignore ├── .gitignore ├── HttpTrigger1 │ ├── function.json │ ├── run.ps1 │ └── sample.dat ├── host.json ├── profile.ps1 └── requirements.psd1 ├── New-PolicyFromTemplate ├── New-PolicyFromTemplate.ps1 └── restExamples │ └── policyTemplates.rest ├── OMA-URI_CheatSheet └── OMA-URI_CheatSheet.pdf ├── PSConfAsia └── Get-WordPressPostSummary.ps1 ├── PowerBI-GraphAuthentication ├── PowerBI_Graph_Authentication.pbit └── PowerBI_Graph_Authentication_Updated.pbit ├── Publish-ScriptToIntune └── Publish-ScriptToIntune.ps1 ├── README.md ├── Registry-Configuration └── Registry-Configuration.ps1 ├── Reset-SidecarScript ├── Reset-SideCarScript.ps1 └── readme.md ├── ScheduledZoomPackager └── Get-ZoomUpdate.ps1 ├── Send-IntuneLogsToFlow └── Send-IntuneLogsToFlow.ps1 ├── Set-RegistryValueForAllUsers └── Set-RegistryValueForAllUsers.ps1 ├── Set-Timezone ├── Set-TimezoneFromIP.ps1 └── Set-TimezoneFromLocation.ps1 ├── Sync-SharepointFolder └── Sync-SharepointFolder.ps1 ├── Universal-Print-Printer-Install ├── Detect.ps1 └── Remediate.ps1 └── Update-AutoPilotGroupTag └── Update-AutoPilotGroupTag.ps1 /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-azurefunctions", 4 | "ms-vscode.PowerShell" 5 | ] 6 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "PowerShell", 6 | "request": "launch", 7 | "name": "PowerShell Launch Current File", 8 | "script": "${file}", 9 | "args": [], 10 | "cwd": "${file}" 11 | }, 12 | { 13 | "type": "PowerShell", 14 | "request": "launch", 15 | "name": "PowerShell Launch Current File in Temporary Console", 16 | "script": "${file}", 17 | "args": [], 18 | "cwd": "${file}", 19 | "createTemporaryIntegratedConsole": true 20 | }, 21 | { 22 | "type": "PowerShell", 23 | "request": "launch", 24 | "name": "PowerShell Launch Current File w/Args Prompt", 25 | "script": "${file}", 26 | "args": [ 27 | "${command:SpecifyScriptArgs}" 28 | ], 29 | "cwd": "${file}" 30 | }, 31 | { 32 | "type": "PowerShell", 33 | "request": "launch", 34 | "name": "PowerShell Launch DebugTest.ps1", 35 | "script": "${workspaceRoot}/DebugTest.ps1", 36 | "args": [ 37 | "-Count 55 -DelayMilliseconds 250" 38 | ], 39 | "cwd": "${workspaceRoot}" 40 | }, 41 | { 42 | "type": "PowerShell", 43 | "request": "launch", 44 | "name": "PowerShell Interactive Session", 45 | "cwd": "${workspaceRoot}" 46 | }, 47 | { 48 | "type": "PowerShell", 49 | "request": "launch", 50 | "name": "PowerShell Pester Tests", 51 | "script": "Invoke-Pester", 52 | "args": [], 53 | "cwd": "${workspaceRoot}" 54 | }, 55 | { 56 | "type": "PowerShell", 57 | "request": "attach", 58 | "name": "PowerShell Attach to Host Process", 59 | "processId": "${command:PickPSHostProcess}", 60 | "runspaceId": 1 61 | }, 62 | { 63 | "name": "Attach to PowerShell Functions", 64 | "type": "PowerShell", 65 | "request": "attach", 66 | "customPipeName": "AzureFunctionsPSWorker", 67 | "runspaceId": 1, 68 | "preLaunchTask": "func: host start" 69 | } 70 | ] 71 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "powershell.codeFormatting.addWhitespaceAroundPipe": true, 3 | "azureFunctions.deploySubpath": "MSI-AzFunction-Demo", 4 | "azureFunctions.projectLanguage": "PowerShell", 5 | "azureFunctions.projectRuntime": "~4", 6 | "debug.internalConsoleOptions": "neverOpen" 7 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "label": "func: host start", 7 | "command": "host start", 8 | "problemMatcher": "$func-powershell-watch", 9 | "isBackground": true, 10 | "options": { 11 | "cwd": "${workspaceFolder}/MSI-AzFunction-Demo" 12 | } 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /Add-GroupMemberByCompliance/Add-GroupMemberByCompliance.ps1: -------------------------------------------------------------------------------- 1 | [cmdletbinding()] 2 | param ( 3 | [parameter(Mandatory = $true)] 4 | [string]$Tenant, 5 | 6 | [parameter(Mandatory = $true)] 7 | [string]$ClientId, 8 | 9 | [parameter(Mandatory = $true)] 10 | [securestring]$ClientSec, 11 | 12 | [parameter(Mandatory = $true)] 13 | [string]$SecGrpId, 14 | 15 | [parameter(Mandatory = $true)] 16 | [int32]$HourOffset 17 | ) 18 | #region Config 19 | [string]$dateFormatted = [datetime]::UtcNow.AddHours($HourOffset).ToString('o') 20 | [string]$baseGraphUri = 'https://graph.microsoft.com/beta' 21 | #endregion 22 | #region Functions 23 | function Invoke-GraphRequest { 24 | [cmdletbinding()] 25 | param ( 26 | [parameter(Mandatory = $false)] 27 | [ValidateSet('Get','Post','Patch','Delete')] 28 | [string]$Method = 'Get', 29 | 30 | [parameter(Mandatory = $true)] 31 | [string]$Query, 32 | 33 | [parameter(Mandatory = $false)] 34 | [string]$Body 35 | ) 36 | $params = @{ 37 | Method = $Method 38 | Uri = $Query 39 | Headers = $script:autHheader 40 | ContentType = 'Application/Json' 41 | } 42 | if ($Body) { 43 | $params.Body = $Body 44 | } 45 | try { 46 | $request = Invoke-RestMethod @params 47 | return $request 48 | } 49 | catch { 50 | Write-Warning $_.Exception.Message 51 | } 52 | } 53 | #endregion 54 | try { 55 | #region Authenticate 56 | $auth = Get-MsalToken -ClientId $ClientId -ClientSecret $ClientSec -TenantId $Tenant 57 | $script:autHheader = @{ 58 | Authorization = $auth.CreateAuthorizationHeader() 59 | } 60 | #endregion 61 | #region Get group & group members 62 | $query = '{0}/groups({1})' -f $baseGraphUri, $("'$SecGrpId'") 63 | $grpData = Invoke-GraphRequest -Query $query 64 | $query = '{0}/members' -f $query 65 | $grpMembers = Invoke-GraphRequest -Query $query 66 | #endregion 67 | #region Get devices based on enrolledDateTime 68 | $query = '{0}/deviceManagement/managedDevices?$filter=enrolledDateTime ge {1}' -f $baseGraphUri, $dateFormatted 69 | $deviceResults = Invoke-GraphRequest -Query $query 70 | #endregion 71 | #region Process results 72 | $deviceResults.value | Where-Object { $_.complianceState -eq 'compliant' } | ForEach-Object { 73 | $device = $_ 74 | #region Grab the AAD object 75 | $query = '{0}/devices?$filter=deviceId eq {1}' -f $baseGraphUri, $("'$($device.azureADDeviceId)'") 76 | $aadObject = Invoke-GraphRequest -Query $query 77 | if ($aadObject.value[0].deviceId -notin $grpMembers.value.deviceId) { 78 | Write-Host "Adding device $($aadObject.value[0].displayName) to group $($grpData.displayName)" 79 | $query = '{0}/groups/{1}/members/$ref' -f $baseGraphUri, $SecGrpId 80 | $body = @{ 81 | '@odata.id' = 'https://graph.microsoft.com/beta/directoryObjects/{0}' -f $aadObject.value[0].id 82 | } | ConvertTo-Json -Depth 20 83 | Invoke-GraphRequest -Method 'Post' -Query $query -Body $body 84 | } 85 | else { 86 | Write-Host "Device $($aadObject.value[0].displayName) already a member of group $($grpData.displayName)" 87 | } 88 | #endregion 89 | } 90 | #endregion 91 | } 92 | catch { 93 | Write-Warning $_.Exception.Message 94 | } 95 | -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/.funcignore: -------------------------------------------------------------------------------- 1 | .git* 2 | .vscode 3 | __azurite_db*__.json 4 | __blobstorage__ 5 | __queuestorage__ 6 | local.settings.json 7 | test -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Azure Functions artifacts 3 | bin 4 | obj 5 | appsettings.json 6 | local.settings.json 7 | 8 | # Azurite artifacts 9 | __blobstorage__ 10 | __queuestorage__ 11 | __azurite_db*__.json -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-azurefunctions", 4 | "ms-vscode.PowerShell" 5 | ] 6 | } -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to PowerShell Functions", 6 | "type": "PowerShell", 7 | "request": "attach", 8 | "customPipeName": "AzureFunctionsPSWorker", 9 | "runspaceId": 1, 10 | "preLaunchTask": "func: host start" 11 | } 12 | ] 13 | } -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.projectLanguage": "PowerShell", 4 | "azureFunctions.projectRuntime": "~4", 5 | "debug.internalConsoleOptions": "neverOpen" 6 | } -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "label": "func: host start", 7 | "command": "host start", 8 | "problemMatcher": "$func-powershell-watch", 9 | "isBackground": true 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/GetDevicesAzPwsh/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "bindings": [ 3 | { 4 | "authLevel": "function", 5 | "type": "httpTrigger", 6 | "route": "{tenantId}/az", 7 | "direction": "in", 8 | "name": "Request", 9 | "methods": [ 10 | "get" 11 | ] 12 | }, 13 | { 14 | "type": "http", 15 | "direction": "out", 16 | "name": "Response" 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/GetDevicesAzPwsh/run.ps1: -------------------------------------------------------------------------------- 1 | using namespace System.Net 2 | 3 | # Input bindings are passed in via param block. 4 | param($Request, $TriggerMetadata) 5 | 6 | # Get the tenant Id from the URL route. 7 | $tenantId = $TriggerMetadata.tenantId 8 | 9 | # using the managed identity token, get an auth token for the tenant 10 | if ($env:MSI_SECRET) { 11 | # get a token for the MSI 12 | $msiToken = Get-AzAccessToken -ResourceUrl "api://AzureADTokenExchange" -AsSecureString 13 | 14 | # using the MSI token, connect to remote tenant. 15 | Connect-azAccount -Tenant $tenantId -ApplicationId $env:CLIENT_ID -FederatedToken $($msiToken.Token | ConvertFrom-SecureString) 16 | 17 | # get an access token for graph 18 | $token = Get-AzAccessToken -ResourceTypeName MSGraph -AsSecureString 19 | } 20 | 21 | #region main process 22 | try { 23 | $devicesUri = 'https://graph.microsoft.com/beta/devices' 24 | $headers = @{ Authorization = "Bearer $($token | ConvertFrom-SecureString)" } 25 | $graphReq = Invoke-RestMethod -Method Get -uri $devicesUri -Headers $headers -ContentType 'application/json' 26 | Write-Output "Devices Found: $($graphReq.value.count)" 27 | $resp = $graphReq.value | ConvertTo-Json -Depth 100 28 | $statusCode = [HttpStatusCode]::OK 29 | $body = $resp 30 | } 31 | catch { 32 | Write-Output $_.Exception.Message 33 | $statusCode = [HttpStatusCode]::BadRequest 34 | $body = $_.Exception.Message 35 | } 36 | 37 | Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 38 | StatusCode = $statusCode 39 | Body = $body 40 | }) 41 | #endregion 42 | -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/GetDevicesAzPwsh/sample.dat: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Azure" 3 | } 4 | -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/GetDevicesDemoPwsh/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "bindings": [ 3 | { 4 | "authLevel": "function", 5 | "type": "httpTrigger", 6 | "route": "{tenantId}/pwsh", 7 | "direction": "in", 8 | "name": "Request", 9 | "methods": [ 10 | "get" 11 | ] 12 | }, 13 | { 14 | "type": "http", 15 | "direction": "out", 16 | "name": "Response" 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/GetDevicesDemoPwsh/run.ps1: -------------------------------------------------------------------------------- 1 | using namespace System.Net 2 | 3 | # Input bindings are passed in via param block. 4 | param($Request, $TriggerMetadata) 5 | 6 | # Get tenant id from url 7 | $tenantId = $TriggerMetadata.tenantId 8 | 9 | #region auth 10 | if ($env:MSI_SECRET) { 11 | # request msi access token 12 | # most guides reference $env:IDENTITY_ENDPOINT and $env:IDENTITY_HEADER 13 | # but for clarity, the values in MSI_ENDPOINT and MSI_SECRET are exactly the same. 14 | # MSI_ENDPOINT is a uri pointing to an internal api endpoint on the app service 15 | # which is usually something like http://localhost:{PORT_NUMBER}/MSI/token/ 16 | # MSI_SECRET is a key that is rotated periodically and is used to protect against SSRF attacks 17 | $resourceUri = 'api://AzureADTokenExchange' 18 | $tokenUri = '{0}?resource={1}&api-version=2019-08-01' -f $env:MSI_ENDPOINT, $resourceURI 19 | $tokenHeader = @{ "X-IDENTITY-HEADER" = $env:MSI_SECRET } 20 | $msiTokenReq = Invoke-RestMethod -Method Get -Headers $tokenHeader -Uri $tokenUri 21 | Write-Host $msiTokenReq 22 | $msiToken = $msiTokenReq.access_token 23 | 24 | # swap msi token for graph access token 25 | $clientTokenReqBody = @{ 26 | client_id = $env:CLIENT_ID 27 | scope = 'https://graph.microsoft.com/.default' 28 | grant_type = "client_credentials" 29 | client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" 30 | client_assertion = $msiToken 31 | } 32 | Write-Host $clientTokenReqBody 33 | $azueAuthURI = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" 34 | $clientAccessTokenReq = Invoke-RestMethod -Method Post -Uri $azueAuthURI -Form $clientTokenReqBody 35 | Write-Host $clientAccessTokenReq 36 | $token = $clientAccessTokenReq.access_token 37 | } 38 | #endregion 39 | 40 | #region main process 41 | try { 42 | $devicesUri = 'https://graph.microsoft.com/beta/devices' 43 | $headers = @{ Authorization = "Bearer $token" } 44 | $graphReq = Invoke-RestMethod -Method Get -uri $devicesUri -Headers $headers -ContentType 'application/json' 45 | Write-Output "Devices Found: $($graphReq.value.count)" 46 | $resp = $graphReq.value | ConvertTo-Json -Depth 100 47 | $statusCode = [HttpStatusCode]::OK 48 | $body = $resp 49 | } 50 | catch { 51 | Write-Output $_.Exception.Message 52 | $statusCode = [HttpStatusCode]::BadRequest 53 | $body = $_.Exception.Message 54 | } 55 | #endregion 56 | 57 | # Associate values to output bindings by calling 'Push-OutputBinding'. 58 | Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 59 | StatusCode = $statusCode ?? [HttpStatusCode]::OK 60 | Body = $body 61 | }) 62 | -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/GetDevicesDemoPwsh/sample.dat: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Azure" 3 | } 4 | -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | }, 11 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[4.*, 5.0.0)" 14 | }, 15 | "managedDependency": { 16 | "enabled": true 17 | } 18 | } -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/profile.ps1: -------------------------------------------------------------------------------- 1 | # Azure Functions profile.ps1 2 | # 3 | # This profile.ps1 will get executed every "cold start" of your Function App. 4 | # "cold start" occurs when: 5 | # 6 | # * A Function App starts up for the very first time 7 | # * A Function App starts up after being de-allocated due to inactivity 8 | # 9 | # You can define helper functions, run commands, or specify environment variables 10 | # NOTE: any variables defined that are not environment variables will get reset after the first execution 11 | 12 | # Authenticate with Azure PowerShell using MSI. 13 | # Remove this if you are not planning on using MSI or Azure PowerShell OR if you don't use Az.Accounts module 14 | if ($env:MSI_SECRET) { 15 | Disable-AzContextAutosave -Scope Process | Out-Null 16 | Connect-AzAccount -Identity 17 | } 18 | 19 | # Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell. 20 | # Enable-AzureRmAlias 21 | 22 | # You can also define functions or aliases that can be referenced in any of your PowerShell functions. 23 | -------------------------------------------------------------------------------- /AzFunctionMultiTenantWI-Demo/requirements.psd1: -------------------------------------------------------------------------------- 1 | # This file enables modules to be automatically managed by the Functions service. 2 | # See https://aka.ms/functionsmanageddependency for additional information. 3 | # Comment this out if you use direct powershell auth method 4 | @{ 5 | 'Az.Accounts' = '4.*' 6 | } -------------------------------------------------------------------------------- /AzTableAPIExamples/AzTableAPIExample.ps1: -------------------------------------------------------------------------------- 1 | #region params 2 | $script:storageAccountName = "" 3 | $script:storageAccountkey = "" #Account key - NOT connection string 4 | $script:tableName = "" 5 | #endregion 6 | #region Functions 7 | function New-AzTableHeader { 8 | param ( 9 | [parameter(Mandatory = $false)] 10 | $StorageAccountName = $script:storageAccountName, 11 | 12 | [parameter(Mandatory = $false)] 13 | $TableName = $script:tableName, 14 | 15 | [parameter(Mandatory = $false)] 16 | $StorageAccountkey = $script:storageAccountkey 17 | ) 18 | $apiVersion = "2017-04-17" 19 | $GMTime = (Get-Date).ToUniversalTime().toString('R') 20 | $string = "$($GMTime)`n/$($storageAccountName)/$($tableName)" 21 | $hmacsha = New-Object System.Security.Cryptography.HMACSHA256 22 | $hmacsha.key = [Convert]::FromBase64String($storageAccountkey) 23 | $signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($string)) 24 | $signature = [Convert]::ToBase64String($signature) 25 | @{ 26 | Authorization = "SharedKeyLite " + $storageAccountName + ":" + $signature 27 | Accept = "application/json;odata=fullmetadata" 28 | 'x-ms-date' = $GMTime 29 | "x-ms-version" = $apiVersion 30 | } 31 | } 32 | function Get-AzTableRowByRowKey { 33 | [cmdletbinding()] 34 | param ( 35 | [parameter(Mandatory = $false)] 36 | $StorageAccountName = $script:storageAccountName, 37 | [parameter(Mandatory = $false)] 38 | $StorageAccountKey = $script:storageAccountkey, 39 | [parameter(Mandatory = $false)] 40 | $TableName = $script:tableName, 41 | [parameter(Mandatory = $true)] 42 | $PartitionKey, 43 | [parameter(Mandatory = $true)] 44 | $RowKey 45 | ) 46 | $headers = New-AzTableHeader -StorageAccountName $StorageAccountName -TableName $TableName -StorageAccountkey $StorageAccountKey 47 | $tableURL = "https://$($storageAccountName).table.core.windows.net/$($tableName)" 48 | $queryURL = "$($tableURL)?`$filter=(PartitionKey eq '$PartitionKey' and RowKey eq '$RowKey')" 49 | $item = Invoke-RestMethod -Method GET -Uri $queryURL -Headers $headers -ContentType 'application/json' 50 | $item.value 51 | } 52 | function Get-AzTableRowByPartitionKey { 53 | [cmdletbinding()] 54 | param ( 55 | [parameter(Mandatory = $false)] 56 | $StorageAccountName = $script:storageAccountName, 57 | [parameter(Mandatory = $false)] 58 | $StorageAccountKey = $script:storageAccountkey, 59 | [parameter(Mandatory = $false)] 60 | $TableName = $script:tableName, 61 | [parameter(Mandatory = $true)] 62 | $PartitionKey 63 | ) 64 | $headers = New-AzTableHeader -StorageAccountName $StorageAccountName -TableName $TableName -StorageAccountkey $StorageAccountKey 65 | $tableURL = "https://$($storageAccountName).table.core.windows.net/$($tableName)" 66 | $queryURL = "$($tableURL)?`$filter=(PartitionKey eq '$PartitionKey')" 67 | $item = Invoke-RestMethod -Method GET -Uri $queryURL -Headers $headers -ContentType 'application/json' 68 | $item.value 69 | } 70 | function Merge-AzTableRow { 71 | [cmdletbinding()] 72 | param ( 73 | [parameter(Mandatory = $false)] 74 | $StorageAccount = $script:storageAccountName, 75 | [parameter(Mandatory = $false)] 76 | $StorageKey = $script:storageAccountkey, 77 | [parameter(Mandatory = $false)] 78 | $TableName = $script:tableName, 79 | [parameter(Mandatory = $true)] 80 | $PartitionKey, 81 | [parameter(Mandatory = $true)] 82 | $RowKey, 83 | [parameter(Mandatory = $true)] 84 | $Entity 85 | ) 86 | $query = "$($TableName)(PartitionKey='$PartitionKey',RowKey='$Rowkey')" 87 | $queryURL = "https://$($storageAccountName).table.core.windows.net/$($query)" 88 | $headers = New-AzTableHeader -StorageAccountName $StorageAccountName -TableName $query -StorageAccountkey $StorageAccountKey 89 | $body = $Entity | ConvertTo-Json 90 | $item = Invoke-RestMethod -Method Merge -Uri $queryURL -Headers $headers -Body $body -ContentType 'application/json' 91 | $item 92 | } 93 | #endregion 94 | #region Example entity 95 | $entity = @{ 96 | PropertyA = "ValueA" 97 | PropertyB = "ValueB" 98 | PropertyC = "ValueC" 99 | PropertyD = "ValueD" 100 | PropertyE = "ValueE" 101 | } 102 | #endregion 103 | #region Example API calls 104 | #add row to table (even if it exists) 105 | Merge-AzTableRow -PartitionKey 'Example' -RowKey $entity.PropertyA -Entity $entity 106 | 107 | #get all partition results 108 | $items = Get-AzTableRowByPartitionKey -PartitionKey 'Example' 109 | 110 | # get single row 111 | $item = Get-AzTableRowByRowKey -PartitionKey 'Example' -RowKey $items[0].RowKey 112 | 113 | #update / merge values to existing row 114 | $change = @{PropertyE = "ValueChanged" } 115 | Merge-AzTableRow -PartitionKey 'Example' -RowKey $item.PropertyA -Entity $change 116 | #endregion -------------------------------------------------------------------------------- /AzureVPNAutoConnect/Deploy-AzureVPNWithAutoConnect.ps1: -------------------------------------------------------------------------------- 1 | #region Config 2 | $VPNName = '' 3 | $VPNGUID = '' # Grab the GUID from the phonebook file or create your own - note that it needs to be a "hexified" guid. 4 | $currentUser = (Get-CimInstance -ClassName WIn32_Process -Filter 'Name="explorer.exe"' | Invoke-CimMethod -MethodName GetOwner)[0] 5 | $objUser = New-Object System.Security.Principal.NTAccount($currentUser.user) 6 | $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier]) 7 | $requiredFolder = "C:\Users\$($currentUser.user)\AppData\Local\Packages\Microsoft.AzureVpn_8wekyb3d8bbwe\LocalState" 8 | $rasManKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\RasMan\Config" 9 | #endregion 10 | #region PBK config 11 | $PBKConfig = @" 12 | # Add your pre-created phonebook configuration here. make sure to replace the Name & GUID with the variables configured above. 13 | "@ 14 | #endregion 15 | #region Functions 16 | function Write-Log { 17 | [cmdletbinding()] 18 | param ( 19 | [string]$logMessage 20 | ) 21 | Write-Host "[$(Get-Date -Format 'dd-MM-yyyy_HH:mm:ss')] $logMessage" -ForegroundColor Yellow 22 | } 23 | function Convert-HexToByte { 24 | [cmdletbinding()] 25 | param ( 26 | [string]$HexString 27 | ) 28 | $splitString = ($HexString -replace '(..)','$1,').Trim(',') 29 | [byte[]]$hexified = $splitString.Split(',') | ForEach-Object { "0x$_"} 30 | return $hexified 31 | } 32 | function Set-ComputerRegistryValues { 33 | param ( 34 | [Parameter(Mandatory = $true)] 35 | [array]$RegistryInstance 36 | ) 37 | try { 38 | foreach ($key in $RegistryInstance) { 39 | $keyPath = $key.Path 40 | if (!(Test-Path $keyPath)) { 41 | Write-Host "Registry path : $keyPath not found. Creating now." -ForegroundColor Green 42 | New-Item -Path $key.Path -Force | Out-Null 43 | Write-Host "Creating item property: $($key.Name)" -ForegroundColor Green 44 | New-ItemProperty -Path $keyPath -Name $key.Name -Value $key.Value -Type $key.Type -Force 45 | } 46 | else { 47 | Write-Host "Creating item property: $($key.Name)" -ForegroundColor Green 48 | New-ItemProperty -Path $keyPath -Name $key.Name -Value $key.Value -Type $key.Type -Force 49 | } 50 | } 51 | } 52 | catch { 53 | Throw $_.Exception.Message 54 | } 55 | } 56 | #endregion 57 | #region deploy VPN 58 | if (!(Test-Path $RequiredFolder -ErrorAction SilentlyContinue)) { 59 | New-Item $RequiredFolder -ItemType Directory | Out-Null 60 | $LogLocation = "$RequiredFolder\NewAzureVPNConnectionLog_$(Get-Date -Format 'dd-MM-yyyy_HH_mm_ss').log" 61 | Start-Transcript -Path $LogLocation -Force -Append 62 | 63 | Write-Log "Required folder $RequiredFolder was created on the machine since it wasn't found." 64 | New-Item "$RequiredFolder\rasphone.pbk" -ItemType File | Out-Null 65 | 66 | Write-Log "File rasphone.pbk has been created in $RequiredFolder." 67 | Set-Content "$RequiredFolder\rasphone.pbk" $PBKConfig 68 | 69 | Write-Log "File rasphone.pbk has been populated with configuration details." 70 | Stop-Transcript | Out-Null 71 | } 72 | else { 73 | $LogLocation = "$RequiredFolder\NewAzureVPNConnectionLog_$(Get-Date -Format 'dd-MM-yyyy_HH_mm_ss').log" 74 | Start-Transcript -Path $LogLocation -Force -Append 75 | 76 | Write-Log "Folder $RequiredFolder already exists, that means that Azure VPN Client is already installed." 77 | if (!(Test-Path "$RequiredFolder\rasphone.pbk" -ErrorAction SilentlyContinue)) { 78 | 79 | Write-Log "File rasphone.pbk doesn't exist in $RequiredFolder." 80 | New-Item "$RequiredFolder\rasphone.pbk" -ItemType File | Out-Null 81 | 82 | Write-Log "File rasphone.pbk has been created in $RequiredFolder." 83 | Set-Content "$RequiredFolder\rasphone.pbk" $PBKConfig 84 | 85 | Write-Log "File rasphone.pbk has been populated with configuration details." 86 | Stop-Transcript | Out-Null 87 | } 88 | else { 89 | Write-Log "File rasphone.pbk already exists in $RequiredFolder." 90 | Rename-Item -Path "$RequiredFolder\rasphone.pbk" -NewName "$RequiredFolder\rasphone.pbk_$(Get-Date -Format 'ddMMyyyy-HHmmss')" 91 | 92 | Write-Log "File rasphone.pbk has been renamed to rasphone.pbk_$(Get-Date -Format 'ddMMyyyy-HHmmss'). This file contains old configuration if it will be required in the future (in case it is, just rename it back to rasphone.pbk)." 93 | New-Item "$RequiredFolder\rasphone.pbk" -ItemType File | Out-Null 94 | 95 | Write-Log "New rasphone.pbk file has been created in $RequiredFolder." 96 | Set-Content "$RequiredFolder\rasphone.pbk" $PBKConfig 97 | 98 | Write-Log "File rasphone.pbk has been populated with configuration details." 99 | Stop-Transcript | Out-Null 100 | } 101 | } 102 | #endregion 103 | #region configure always on 104 | [string[]]$autoDisable = (Get-ItemPropertyValue $rasManKeyPath -Name AutoTriggerDisabledProfilesList) | ForEach-Object { if ($_ -ne $VPNName) { $_ }} 105 | $regKeys = @( 106 | @{ 107 | Path = $rasManKeyPath 108 | Name = 'AutoTriggerDisabledProfilesList' 109 | Value = [string[]]$autoDisable 110 | Type = 'MultiString' 111 | } 112 | @{ 113 | Path = $rasManKeyPath 114 | Name = 'AutoTriggerProfilePhonebookPath' 115 | Value = "$RequiredFolder\rasphone.pbk" 116 | Type = 'String' 117 | } 118 | @{ 119 | Path = $rasManKeyPath 120 | Name = 'AutoTriggerProfileEntryName' 121 | Value = $VPNName 122 | Type = 'String' 123 | } 124 | @{ 125 | Path = $rasManKeyPath 126 | Name = 'UserSID' 127 | Value = $sid 128 | Type = 'String' 129 | } 130 | @{ 131 | Path = $rasManKeyPath 132 | Name = 'AutoTriggerProfileGUID' 133 | Value = [Byte[]](Convert-HexToByte -HexString $VPNGUID) 134 | Type = 'Binary' 135 | } 136 | ) 137 | Set-ComputerRegistryValues $regKeys 138 | #endregion 139 | #region Extra Credit - Dial the VPN. Delete this if you don't need it. 140 | . rasdial $vpnName /PHONEBOOK:$RequiredFolder\rasphone.pbk 141 | #endregion -------------------------------------------------------------------------------- /CertificateExpiration/Get-CertificateExpiry.ps1: -------------------------------------------------------------------------------- 1 | #region config 2 | $config = @{ 3 | tenantId = "powers-hell.com" 4 | appId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" 5 | clientSecret = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" 6 | dayThreshold = 7 7 | } 8 | #endregion 9 | 10 | #region functions 11 | function Get-AuthHeader { 12 | [cmdletbinding()] 13 | param ( 14 | [parameter(Mandatory = $true)] 15 | [string]$TenantId, 16 | [parameter(Mandatory = $true)] 17 | [string]$ApplicationId, 18 | [parameter(Mandatory = $true)] 19 | [string]$ClientSecret 20 | ) 21 | $requestBody = @{ 22 | resource = 'https://graph.microsoft.com' 23 | client_id = $ApplicationId 24 | client_secret = $clientSecret 25 | grant_type = "client_credentials" 26 | scope = "openid" 27 | } 28 | 29 | $authParams = @{ 30 | Method = 'Post' 31 | Uri = "https://login.microsoftonline.com/$TenantId/oauth2/token" 32 | Body = $requestBody 33 | } 34 | $auth = Invoke-RestMethod @authParams 35 | $authorizationHeader = @{ 36 | Authorization = "Bearer $($auth.access_token)" 37 | } 38 | return $authorizationHeader 39 | } 40 | 41 | function Get-TrustedCertificatesFromIntune { 42 | [cmdletbinding()] 43 | param ( 44 | [parameter(Mandatory = $true)] 45 | [hashtable]$AuthHeader 46 | ) 47 | 48 | try { 49 | #region Query Graph 50 | $baseUri = 'https://graph.microsoft.com/beta/deviceManagement/deviceConfigurations' 51 | $graphParams = @{ 52 | Method = 'Get' 53 | Uri = $baseUri 54 | Headers = $AuthHeader 55 | ContentType = 'Application/Json' 56 | } 57 | $result = Invoke-RestMethod @graphParams 58 | $resultValue = $result.value.Count -gt 0 ? $result.value : $null 59 | #endregion 60 | #region Format the results 61 | $foundCertificates = $resultValue | Where-Object { $_.'@odata.type' -like "#microsoft.graph.*TrustedRootCertificate" } 62 | if ($foundCertificates.Count -gt 0) { 63 | Write-Verbose "$($foundCertificates.Count) Trusted certificates found" 64 | return $foundCertificates 65 | } 66 | #endregion 67 | } 68 | catch { 69 | Write-Warning $_.Exception.Message 70 | } 71 | } 72 | 73 | function Get-CertificateDataFromTrustedCertificatePolicy { 74 | [cmdletbinding()] 75 | param ( 76 | [parameter(Mandatory = $True, ValueFromPipeline)] 77 | [PSCustomObject]$TrustedRootCertificate 78 | ) 79 | try { 80 | $decryptedTRC = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($TrustedRootCertificate.trustedRootCertificate)) 81 | if ($decryptedTRC -match "-----BEGIN CERTIFICATE-----") { 82 | #region base64 encoded certificate detected 83 | Write-Verbose "Base64 encoded certificate detected.." 84 | $formattedCertContent = ($decryptedTRC -replace "-----BEGIN CERTIFICATE-----|-----END CERTIFICATE-----", "").Trim() 85 | $decryptedCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]([System.Convert]::FromBase64String($formattedCertContent)) 86 | return $decryptedCertificate 87 | #endregion 88 | } 89 | else { 90 | #region der encoded certificate detected 91 | Write-Verbose "Der encoded certificate detected.." 92 | [byte[]]$decryptedDerTRC = [System.Convert]::FromBase64String($TrustedRootCertificate.trustedRootCertificate) 93 | $decryptedCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]($decryptedDerTRC) 94 | return $decryptedCertificate 95 | #endregion 96 | } 97 | } 98 | catch { 99 | Write-Warning $_.Exception.Message 100 | } 101 | } 102 | #endregion 103 | 104 | #region auth 105 | $authHeader = Get-AuthHeader -TenantId $config.tenantId -ApplicationId $config.appId -ClientSecret $config.clientSecret 106 | #endregion 107 | 108 | #region grab certificate profiles 109 | $certificateProfiles = Get-TrustedCertificatesFromIntune -AuthHeader $authHeader 110 | #endregion 111 | 112 | #region grab certicate metadata and send alerts if certificate expires within set threshold 113 | Write-Host ([system.environment]::NewLine) 114 | $Expiringcertificates = foreach ($cert in $certificateProfiles) { 115 | $certData = Get-CertificateDataFromTrustedCertificatePolicy -TrustedRootCertificate $cert 116 | $daysRemaining = [math]::Round((($certData.NotAfter) - ($dn)).TotalDays) 117 | if ($daysRemaining -lt $config.dayThreshold) { 118 | Write-Host "$($cert.displayName) expires in $daysRemaining days ⚠️⚠️⚠️" 119 | $certData 120 | } 121 | } 122 | Write-Host ([system.environment]::NewLine) 123 | #endregion -------------------------------------------------------------------------------- /DemoModule/.gitignore: -------------------------------------------------------------------------------- 1 | .tests 2 | .vscode 3 | bin 4 | .exe 5 | .msi 6 | .nupkg -------------------------------------------------------------------------------- /DemoModule/DemoModule/DemoModule.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/DemoModule/DemoModule/DemoModule.psd1 -------------------------------------------------------------------------------- /DemoModule/DemoModule/DemoModule.psm1: -------------------------------------------------------------------------------- 1 | # Implement your module commands in this script. 2 | [string]$script:randomInt = Get-Random -Maximum 7 -Minimum 0 3 | # Get public and private function definition files. 4 | $Public = @(Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue) 5 | $Private = @(Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue) 6 | # Dot source the files 7 | foreach ($import in @($Public + $Private)) 8 | { 9 | try 10 | { 11 | . $import.FullName 12 | } 13 | catch 14 | { 15 | Write-Error -Message "Failed to import function $($import.FullName): $_" 16 | } 17 | } -------------------------------------------------------------------------------- /DemoModule/DemoModule/Private/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/DemoModule/DemoModule/Private/.gitkeep -------------------------------------------------------------------------------- /DemoModule/DemoModule/Private/Get-RandomPlanet.ps1: -------------------------------------------------------------------------------- 1 | function Get-RandomPlanet { 2 | [cmdletbinding()] 3 | param ( 4 | [parameter(Mandatory = $true)] 5 | [string]$planetInt 6 | ) 7 | $planets = @( 8 | "Mercury", 9 | "Venus", 10 | "Earth", 11 | "Mars", 12 | "Jupiter", 13 | "Saturn", 14 | "Uranus", 15 | "Neptune" 16 | ) 17 | return $planets[$planetInt] 18 | } -------------------------------------------------------------------------------- /DemoModule/DemoModule/Public/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/DemoModule/DemoModule/Public/.gitkeep -------------------------------------------------------------------------------- /DemoModule/DemoModule/Public/Invoke-PlanetGreeting.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-PlanetGreeting { 2 | [cmdletbinding()] 3 | param ( 4 | [parameter(Mandatory = $false)] 5 | [string]$planet = $script:randomInt 6 | ) 7 | $planet = Get-RandomPlanet -PlanetInt $planet 8 | return "Hello $planet`!" 9 | } -------------------------------------------------------------------------------- /DemoModule/DemoModule/Public/Test-OddOrEven.ps1: -------------------------------------------------------------------------------- 1 | function Test-OddOrEven { 2 | [cmdletbinding()] 3 | param ( 4 | [parameter(Mandatory = $true)] 5 | [int]$Integer 6 | ) 7 | switch ($Integer % 2) { 8 | 0 { 9 | return "$Integer is even" 10 | } 11 | 1 { 12 | return "$Integer is odd" 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /DemoModule/DemoModule/ReleaseNotes.txt: -------------------------------------------------------------------------------- 1 | Initial Release -------------------------------------------------------------------------------- /DemoModule/DemoModule/description.txt: -------------------------------------------------------------------------------- 1 | A demo module to say hello to our solar system -------------------------------------------------------------------------------- /DemoModule/README.md: -------------------------------------------------------------------------------- 1 | # DemoModule 2 | 3 | ## Summary 4 | 5 | A Demo Module - nothing more. 6 | 7 | 8 | ## Usage 9 | 10 | * Install the module. 11 | * Run the public function. 12 | * Say hello to the planets. 13 | 14 | ## Release Notes 15 | 16 | * v1.0.0.x Initial release of module. -------------------------------------------------------------------------------- /DemoModule/build.ps1: -------------------------------------------------------------------------------- 1 | [cmdletbinding()] 2 | param ( 3 | [parameter(Mandatory = $true)] 4 | [System.IO.FileInfo]$modulePath 5 | ) 6 | try { 7 | #region Generate a new version number 8 | $moduleName = Split-Path $modulePath -Leaf 9 | [Version]$exVer = Find-Module $moduleName -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Version 10 | $newVersion = if ($exVer) { 11 | $rev = ($exVer.Revision + 1) 12 | New-Object version -ArgumentList $exVer.Major, $exVer.Minor, $exVer.Build, $rev 13 | } 14 | else { 15 | $rev = ((Get-ChildItem $PSScriptRoot\bin\release\ -ErrorAction SilentlyContinue).Name | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum) + 1 16 | New-Object Version -ArgumentList 1, 0, 0, $rev 17 | 18 | } 19 | #endregion 20 | #region Build out the release 21 | $relPath = "$PSScriptRoot\bin\release\$rev\$moduleName" 22 | "Version is $newVersion" 23 | "Module Path is $modulePath" 24 | "Module Name is $moduleName" 25 | "Release Path is $relPath" 26 | if (!(Test-Path $relPath)) { 27 | New-Item -Path $relPath -ItemType Directory -Force | Out-Null 28 | } 29 | Copy-Item "$modulePath\*" -Destination "$relPath" -Recurse -Exclude ".gitKeep" 30 | #endregion 31 | #region Generate a list of public functions and update the module manifest 32 | $functions = @(Get-ChildItem -Path $relPath\Public\*.ps1 -ErrorAction SilentlyContinue).basename 33 | Update-ModuleManifest -Path $relPath\$ModuleName.psd1 -ModuleVersion $newVersion -FunctionsToExport $functions 34 | $moduleManifest = Get-Content $relPath\$ModuleName.psd1 -Raw | Invoke-Expression 35 | #endregion 36 | } 37 | catch { 38 | $_ 39 | } -------------------------------------------------------------------------------- /Dynamic-Group-Automation/.funcignore: -------------------------------------------------------------------------------- 1 | .git* 2 | .vscode 3 | local.settings.json 4 | test -------------------------------------------------------------------------------- /Dynamic-Group-Automation/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Azure Functions artifacts 3 | bin 4 | obj 5 | appsettings.json 6 | local.settings.json -------------------------------------------------------------------------------- /Dynamic-Group-Automation/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-azurefunctions", 4 | "ms-vscode.PowerShell" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /Dynamic-Group-Automation/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to PowerShell Functions", 6 | "type": "PowerShell", 7 | "request": "attach", 8 | "customPipeName": "AzureFunctionsPSWorker", 9 | "runspaceId": 1, 10 | "preLaunchTask": "func: host start" 11 | } 12 | ] 13 | } -------------------------------------------------------------------------------- /Dynamic-Group-Automation/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.projectLanguage": "PowerShell", 4 | "azureFunctions.projectRuntime": "~3", 5 | "debug.internalConsoleOptions": "neverOpen" 6 | } -------------------------------------------------------------------------------- /Dynamic-Group-Automation/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "command": "host start", 7 | "problemMatcher": "$func-powershell-watch", 8 | "isBackground": true 9 | } 10 | ] 11 | } -------------------------------------------------------------------------------- /Dynamic-Group-Automation/Dynamic-Group-Function/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "bindings": [ 3 | { 4 | "authLevel": "function", 5 | "type": "httpTrigger", 6 | "direction":"in", 7 | "name": "Request", 8 | "methods": [ 9 | "post" 10 | ] 11 | }, 12 | { 13 | "type": "http", 14 | "direction": "out", 15 | "name": "Response" 16 | } 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /Dynamic-Group-Automation/Dynamic-Group-Function/run.ps1: -------------------------------------------------------------------------------- 1 | using namespace System.Net 2 | # Input bindings are passed in via param block. 3 | param($Request, $TriggerMetadata) 4 | $result = [System.Collections.ArrayList]::new() 5 | $expectedComplianceValue = "noncompliant" 6 | <# 7 | Make sure the following application settings // 8 | variables are configured before running 9 | | Variable Name | Variable Value | 10 | |--- |--- | 11 | | TENANT_ID | **Your tenant ID \ AAD domain name** | 12 | | APPLICATION_ID | **Your AAD application ID** | 13 | | CLIENT_SECRET | **Your AAD application client secret** | 14 | | GROUP_ID | **The object id of the security group you want to manage**| 15 | #> 16 | #region functions 17 | function Get-AuthHeader { 18 | param ( 19 | [Parameter(mandatory = $true)] 20 | [string]$TenantId, 21 | [Parameter(mandatory = $true)] 22 | [string]$ClientId, 23 | [Parameter(mandatory = $true)] 24 | [string]$ClientSecret, 25 | [Parameter(mandatory = $true)] 26 | [string]$ResourceUrl 27 | ) 28 | $body = @{ 29 | resource = $ResourceUrl 30 | client_id = $ClientId 31 | client_secret = $ClientSecret 32 | grant_type = "client_credentials" 33 | scope = "openid" 34 | } 35 | try { 36 | $response = Invoke-RestMethod -Method post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/token" -Body $body -ErrorAction Stop 37 | $headers = @{ "Authorization" = "Bearer $($response.access_token)" } 38 | return $headers 39 | } 40 | catch { 41 | Write-Error $_.Exception 42 | } 43 | } 44 | function Invoke-GraphCall { 45 | [cmdletbinding()] 46 | param ( 47 | [parameter(Mandatory = $false)] 48 | [ValidateSet('Get', 'Post', 'Delete')] 49 | [string]$Method = 'Get', 50 | 51 | [parameter(Mandatory = $false)] 52 | [hashtable]$Headers = $script:authHeader, 53 | 54 | [parameter(Mandatory = $true)] 55 | [string]$Uri, 56 | 57 | [parameter(Mandatory = $false)] 58 | [string]$ContentType = 'Application/Json', 59 | 60 | [parameter(Mandatory = $false)] 61 | [hashtable]$Body 62 | ) 63 | try { 64 | $params = @{ 65 | Method = $Method 66 | Headers = $Headers 67 | Uri = $Uri 68 | ContentType = $ContentType 69 | } 70 | if ($Body) { 71 | $params.Body = $Body | ConvertTo-Json -Depth 20 72 | } 73 | $query = Invoke-RestMethod @params 74 | return $query 75 | } 76 | catch { 77 | Write-Warning $_.Exception.Message 78 | } 79 | } 80 | function Format-Result { 81 | [cmdletbinding()] 82 | param ( 83 | [parameter(Mandatory = $true)] 84 | [string]$DeviceID, 85 | 86 | [parameter(Mandatory = $true)] 87 | [bool]$IsCompliant, 88 | 89 | [parameter(Mandatory = $true)] 90 | [bool]$IsMember, 91 | 92 | [parameter(Mandatory = $true)] 93 | [ValidateSet('Added', 'Removed', 'NoActionTaken')] 94 | [string]$Action 95 | ) 96 | $result = [PSCustomObject]@{ 97 | DeviceID = $DeviceID 98 | IsCompliant = $IsCompliant 99 | IsMember = $IsMember 100 | Action = $Action 101 | } 102 | return $result 103 | } 104 | #endregion 105 | #region authentication 106 | $params = @{ 107 | TenantId = $env:TENANT_ID 108 | ClientId = $env:CLIENT_ID 109 | ClientSecret = $env:CLIENT_SECRET 110 | ResourceUrl = "https://graph.microsoft.com" 111 | } 112 | $script:authHeader = Get-AuthHeader @params 113 | #endregion 114 | #region get devices & group members 115 | $graphUri = 'https://graph.microsoft.com/Beta/deviceManagement/managedDevices' 116 | $query = Invoke-GraphCall -Uri $graphUri 117 | 118 | $graphUri = "https://graph.microsoft.com/beta/groups/$env:GROUP_ID/members" 119 | $groupMembers = Invoke-GraphCall -Uri $graphUri 120 | #endregion 121 | #region check each device. 122 | foreach ($device in $query.value) { 123 | #region get aad object from intune object 124 | $graphUri = "https://graph.microsoft.com/beta/devices?`$filter=deviceId eq '$($device.azureADDeviceId)'" 125 | $AADDevice = (Invoke-GraphCall -Uri $graphUri).value 126 | #endregion 127 | if ($device.complianceState -eq $expectedComplianceValue) { 128 | if ($groupMembers.value.deviceId -notcontains $AADDevice.deviceId) { 129 | #region Device is compliant and not in the group 130 | $graphUri = "https://graph.microsoft.com/v1.0/groups/$env:GROUP_ID/members/`$ref" 131 | $body = @{"@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/$($AADDevice.id)" } 132 | Invoke-GraphCall -Uri $graphUri -Method Post -Body $body 133 | $result.Add($(Format-Result -DeviceID $device.id -IsCompliant $true -IsMember $true -Action Added)) | Out-Null 134 | #endregion 135 | } 136 | else { 137 | #region device is compliant and already a member 138 | $result.Add($(Format-Result -DeviceID $device.id -IsCompliant $true -IsMember $true -Action NoActionTaken)) | Out-Null 139 | #endregion 140 | } 141 | } 142 | else { 143 | if ($groupMembers.value.deviceId -contains $AADDevice.deviceId) { 144 | #region device not compliant and exists in group 145 | $graphUri = "https://graph.microsoft.com/v1.0/groups/$env:GROUP_ID/members/$($AADDevice.id)/`$ref" 146 | Invoke-GraphCall -Uri $graphUri -Method Delete 147 | $result.Add($(Format-Result -DeviceID $device.id -IsCompliant $false -IsMember $false -Action Removed)) | Out-Null 148 | #endregion 149 | } 150 | else { 151 | #region device not compliant and is not a member 152 | $result.Add($(Format-Result -DeviceID $device.id -IsCompliant $false -IsMember $false -Action NoActionTaken)) 153 | #endregion 154 | } 155 | } 156 | } 157 | #endregion 158 | # Associate values to output bindings by calling 'Push-OutputBinding'. 159 | Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 160 | StatusCode = [HttpStatusCode]::OK 161 | Body = $result | ConvertTo-Json -Depth 20 162 | }) -------------------------------------------------------------------------------- /Dynamic-Group-Automation/Dynamic-Group-Function/sample.dat: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Azure" 3 | } 4 | -------------------------------------------------------------------------------- /Dynamic-Group-Automation/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | }, 11 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[2.*, 3.0.0)" 14 | }, 15 | "managedDependency": { 16 | "enabled": false 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Dynamic-Group-Automation/profile.ps1: -------------------------------------------------------------------------------- 1 | # Azure Functions profile.ps1 2 | # 3 | # This profile.ps1 will get executed every "cold start" of your Function App. 4 | # "cold start" occurs when: 5 | # 6 | # * A Function App starts up for the very first time 7 | # * A Function App starts up after being de-allocated due to inactivity 8 | # 9 | # You can define helper functions, run commands, or specify environment variables 10 | # NOTE: any variables defined that are not environment variables will get reset after the first execution 11 | 12 | # Authenticate with Azure PowerShell using MSI. 13 | # Remove this if you are not planning on using MSI or Azure PowerShell. 14 | if ($env:MSI_SECRET) { 15 | Disable-AzContextAutosave -Scope Process | Out-Null 16 | Connect-AzAccount -Identity 17 | } 18 | 19 | # Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell. 20 | # Enable-AzureRmAlias 21 | 22 | # You can also define functions or aliases that can be referenced in any of your PowerShell functions. 23 | -------------------------------------------------------------------------------- /Dynamic-Group-Automation/proxies.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/proxies", 3 | "proxies": {} 4 | } 5 | -------------------------------------------------------------------------------- /Dynamic-Group-Automation/requirements.psd1: -------------------------------------------------------------------------------- 1 | # This file enables modules to be automatically managed by the Functions service. 2 | # See https://aka.ms/functionsmanageddependency for additional information. 3 | # 4 | @{ 5 | # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 6 | # To use the Az module in your function app, please uncomment the line below. 7 | # 'Az' = '6.*' 8 | } -------------------------------------------------------------------------------- /Expand-Intunewin/Decrypt-IntuneFromLogs.ps1: -------------------------------------------------------------------------------- 1 | function Decrypt($base64string) { 2 | [System.Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null 3 | 4 | $content = [Convert]::FromBase64String($base64string) 5 | $envelopedCms = New-Object Security.Cryptography.Pkcs.EnvelopedCms 6 | $certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection 7 | $envelopedCms.Decode($content) 8 | $envelopedCms.Decrypt($certCollection) 9 | 10 | $utf8content = [text.encoding]::UTF8.getstring($envelopedCms.ContentInfo.Content) 11 | 12 | return $utf8content 13 | } 14 | 15 | $agentLogPath = Join-Path $env:ProgramData "Microsoft\IntuneManagementExtension\Logs\IntuneManagementExtension.log" 16 | $stringToSearch = " 12 | param ( 13 | [string]$server, 14 | 15 | [string]$printerName 16 | ) 17 | $printerPath = $null 18 | $PrinterPath = "\\$($server)\$($printerName)" 19 | $netConn = Test-NetConnection -ComputerName $Server | select-object PingSucceeded, NameResolutionSucceeded 20 | if (($netconn.PingSucceeded) -and ($netConn.NameResolutionSucceeded)) { 21 | write-host "Installing $printerName.." -ForegroundColor Green 22 | if (Get-Printer -Name "$printerPath" -ErrorAction SilentlyContinue) { 23 | Write-Host "Printer $printerPath already installed" -ForegroundColor Green 24 | } 25 | else { 26 | Write-Host "Installing $printerPath" -ForegroundColor Green 27 | & cscript /noLogo C:\windows\System32\Printing_Admin_Scripts\en-US\prnmngr.vbs -ac -p $printerPath 28 | if (Get-Printer -Name "$printerPath" -ErrorAction SilentlyContinue) { 29 | Write-Host "$printerPath successfully installed.." 30 | } 31 | else { 32 | Write-Warning "$printerPath not successfully installed" 33 | } 34 | } 35 | } 36 | else { 37 | Write-Host "Print server not pingable. $printerPath will not be installed" -ForegroundColor Red 38 | } 39 | } 40 | #endregion 41 | #region Printers to install 42 | $printers = @( 43 | [PSCustomObject]@{ 44 | Printer = "MainPrinter" 45 | Server = "print1.powers-hell.com" 46 | } 47 | [PSCustomObject]@{ 48 | Printer = "FrontDeskPrinter" 49 | Server = "print1.powers-hell.com" 50 | } 51 | [PSCustomObject]@{ 52 | Printer = "BackupPrinter" 53 | Server = "print2.powers-hell.com" 54 | } 55 | ) 56 | #endregion 57 | #region Install printers 58 | foreach ($p in $printers) { 59 | Set-LocalPrinters -server $p.Server -printerName $p.Printer 60 | } 61 | #endregion 62 | -------------------------------------------------------------------------------- /IntuneMonitoring/IntuneConfigMonitoring/IntuneConfigMonitoring.ps1: -------------------------------------------------------------------------------- 1 | $fp = $EXECUTION_CONTEXT_FUNCTIONDIRECTORY 2 | $config = Get-Content "$fp/appConfig.json" -Raw | ConvertFrom-Json 3 | $tenant = $config.basicConfig.tenant 4 | $query = $config.basicConfig.query 5 | $graphConnectorURI = $config.basicConfig.graphConnectorURI 6 | $graphVer = $config.basicConfig.graphVer 7 | $graphQuery = "deviceManagement/$($query)" 8 | $currentSnapshot = $ExecutionContext.InvokeCommand.ExpandString($config.basicConfig.currentSnapshot) 9 | Function Compare-ObjectProperties { 10 | # cleaned up from https://blogs.technet.microsoft.com/janesays/2017/04/25/compare-all-properties-of-two-objects-in-windows-powershell/ 11 | Param( 12 | [PSObject]$ReferenceObject, 13 | [PSObject]$DifferenceObject 14 | ) 15 | $objprops = $ReferenceObject | Get-Member -MemberType Property, NoteProperty | ForEach-Object Name 16 | $objprops += $DifferenceObject | Get-Member -MemberType Property, NoteProperty | ForEach-Object Name 17 | $objprops = $objprops | Sort-Object | Select-Object -Unique 18 | $diffs = @() 19 | foreach ($objprop in $objprops) { 20 | $diff = Compare-Object $ReferenceObject $DifferenceObject -Property $objprop 21 | if ($diff) { 22 | $diffprops = @{ 23 | PropertyName = $objprop 24 | RefValue = ($diff | Where-Object {$_.SideIndicator -eq '<='} | ForEach-Object $($objprop)) 25 | DiffValue = ($diff | Where-Object {$_.SideIndicator -eq '=>'} | ForEach-Object $($objprop)) 26 | } 27 | $diffs += New-Object PSObject -Property $diffprops 28 | } 29 | } 30 | if ($diffs) {return ($diffs | Select-Object PropertyName, RefValue, DiffValue)} 31 | } 32 | 33 | $intuneSnapshot = Invoke-RestMethod -Uri $currentSnapshot 34 | 35 | $graphURI = "$($graphConnectorURI)&tenant=$($tenant)&Ver=$($graphVer)&query=$($graphQuery)" 36 | $latestCapture = Invoke-RestMethod -Method Get -Uri $graphURI 37 | $results = @() 38 | for ($i = 0; $i -le ($intuneSnapshot.count - 1) ; $i ++) { 39 | $tmpCompare = Compare-ObjectProperties -ReferenceObject $intuneSnapshot[$i] -DifferenceObject $latestCapture[$i] 40 | if ($tmpCompare) { 41 | $tmpobject = [psCustomObject]@{ 42 | TimeStamp = Get-date -Format "yyyy-MM-ddTHH:mm:ss" 43 | Tenant = $tenant 44 | ChangesFound = $true 45 | SnapshotObject = $intuneSnapshot[$i] 46 | ModifiedObject = $latestCapture[$i] 47 | ChangedProperties = $tmpCompare 48 | } 49 | $results += $tmpobject 50 | } 51 | } 52 | if ($results) { 53 | return $results | ConvertTo-Json | out-file -encoding ascii -FilePath $res 54 | } 55 | else { 56 | $tmpObject = [psCustomObject]@{ 57 | TimeStamp = Get-date -Format "yyyy-MM-ddTHH:mm:ss" 58 | Tenant = $tenant 59 | ChangesFound = $false 60 | } 61 | return $tmpObject | ConvertTo-Json | out-file -encoding ascii -FilePath $res 62 | } -------------------------------------------------------------------------------- /IntuneMonitoring/IntuneConfigMonitoring/appConfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "BasicConfig": 3 | { 4 | "tenant" : "contoso.com.au", 5 | "query" : "deviceManagementScripts", 6 | "currentSnapshot" : "https://storageaccountURL.blob.core.windows.net/ContainerName/$($tenant)_$($query).json?SuperSecretSASCode", 7 | "graphConnectorURI" : "https://graphconnectorPOC.azurewebsites.net/api/GraphConnector?code=SuperSecretCode", 8 | "graphVer": "beta" 9 | } 10 | } -------------------------------------------------------------------------------- /IntuneMonitoring/IntuneConfigSnapshot/IntuneConfigSnapshot.ps1: -------------------------------------------------------------------------------- 1 | $requestBody = Get-Content $req -Raw | ConvertFrom-Json 2 | $fp = $EXECUTION_CONTEXT_FUNCTIONDIRECTORY 3 | $config = Get-Content "$fp/appConfig.json" -Raw | ConvertFrom-Json 4 | $graphConnectorURI = $config.basicConfig.graphConnectorURI 5 | $tenant = $requestBody.tenant 6 | $ver = $config.basicConfig.graphVer 7 | $query = "deviceManagement/$($requestBody.query)" 8 | $graphURI = "$($graphConnectorURI)&tenant=$($tenant)&Ver=$($ver)&query=$($query)" 9 | $objResult = Invoke-RestMethod -Method Get -Uri $graphURI 10 | 11 | $objResult | ConvertTo-Json -Depth 20 | out-file -Encoding ascii -FilePath $outputBlob 12 | 13 | if ($objResult) { 14 | $result = $true 15 | } 16 | else { 17 | $result = $false 18 | } 19 | $objReturn = [pscustomobject]@{ 20 | Date = Get-Date -Format "yyyy-MM-ddTHH:mm:ss" 21 | Result = $result 22 | } 23 | write-output $outputBlob 24 | $objReturn | ConvertTo-Json | out-file -Encoding ascii -FilePath $res -------------------------------------------------------------------------------- /IntuneMonitoring/IntuneConfigSnapshot/appConfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "BasicConfig": 3 | { 4 | "graphConnectorURI" : "https://functionURL.azurewebsites.net/api/FunctionName?code=SuperSecreCode==", 5 | "graphVer" : "beta" 6 | } 7 | } -------------------------------------------------------------------------------- /IntuneMonitoring/readme.md: -------------------------------------------------------------------------------- 1 | # IntuneMonitoring 2 | Source code for blog post titled "Monitor changes to Intune using Azure Functions, GraphAI & PowerShell" found on https://www.powers-hell.com -------------------------------------------------------------------------------- /Invoke-GraphConnector/Invoke-GraphConnector.ps1: -------------------------------------------------------------------------------- 1 | # POST method: $req 2 | $requestBody = Get-Content $req -Raw | ConvertFrom-Json 3 | $tenant = $requestBody.tenant 4 | 5 | # GET method: each querystring parameter is its own variable 6 | if ($req_query_tenant) { 7 | $tenant = $req_query_tenant 8 | } 9 | if ($req_query_query) { 10 | $query = $req_query_query 11 | } 12 | if ($req_query_ver) { 13 | $ver = $req_query_ver 14 | } 15 | else { 16 | $ver = 'v1.0' 17 | } 18 | if ($req_query_space) { 19 | $space = $req_query_space 20 | } 21 | else { 22 | $space = "AAD" 23 | } 24 | $fp = $EXECUTION_CONTEXT_FUNCTIONDIRECTORY 25 | $config = Get-Content "$fp/appConfig.json" -Raw | ConvertFrom-Json 26 | $account = $config.accounts | Where-Object {$_.strTd -eq "$tenant"} 27 | $GLOBAL:adal = "$fp/Microsoft.IdentityModel.Clients.ActiveDirectory.dll" 28 | $GLOBAL:adalforms = "$fp/Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" 29 | 30 | 31 | <# 32 | .Synopsis 33 | simple script to retrieve Graph API Access Token and create the correctly formed header object. 34 | .EXAMPLE 35 | .\Get-AuthHeader -un "ben@tenantdomain.onmicrosoft.com" -pw 'password' 36 | .EXAMPLE 37 | .\Get-AuthHeader -un "ben@tenantdomain.onmicrosoft.com" -pw 'password' 38 | .INPUTS 39 | $un - email address of account to be used to authenticate to tenant domain / graph API 40 | $pw - password of account. if more than simple characters, try and wrap in single quotes. 41 | #> 42 | function Get-AuthHeader { 43 | param ( 44 | [Parameter(Mandatory = $true)] 45 | $un, 46 | [Parameter(Mandatory = $true)] 47 | $pw, 48 | [parameter(mandatory = $true)] [ValidateSet('Intune', 'AAD')] 49 | $space 50 | ) 51 | 52 | [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null 53 | 54 | [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null 55 | 56 | $userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $un 57 | $tenantDomain = $userUpn.Host 58 | switch ($space) { 59 | "Intune" { 60 | $cId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" 61 | break; 62 | } 63 | "AAD" { 64 | $cId = "1950a258-227b-4e31-a9cf-717495945fc2" 65 | break; 66 | } 67 | } 68 | 69 | $resourceAppIdURI = "https://graph.microsoft.com" 70 | $authString = "https://login.microsoftonline.com/$tenantDomain" 71 | 72 | $pw = $pw | ConvertTo-SecureString -AsPlainText -Force 73 | $cred = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential -ArgumentList $userUpn, $pw 74 | $authContext = new-object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authString 75 | try { 76 | $authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceAppIdURI, $cId, $cred).Result 77 | if ($authResult.AccessToken) { 78 | 79 | # Creating header for Authorization token 80 | 81 | $authHeader = @{ 82 | 'Content-Type' = 'application/json' 83 | 'Authorization' = "Bearer " + $authResult.AccessToken 84 | 'ExpiresOn' = $authResult.ExpiresOn 85 | } 86 | 87 | return $authHeader 88 | } 89 | else { 90 | throw; 91 | } 92 | } 93 | Catch { 94 | return $false 95 | } 96 | } 97 | <# 98 | .Synopsis 99 | simple script to form Graph API URLs and deliver the results as a JSON Payload. 100 | .EXAMPLE 101 | .\Get-JsonFromGraph -strUn "ben@tenantdomain.onmicrosoft.com" -strPw 'password' -strQuery "Users" -ver 1.0 102 | .EXAMPLE 103 | .\Get-JsonFromGraph -strUn "ben@tenantdomain.onmicrosoft.com" -strPw 'password' -strQuery "ManagedDevices" -ver beta 104 | .INPUTS 105 | $strUn - email address of account to be used to authenticate to tenant domain / graph API 106 | $strPw - password of account. if more than simple characters, wrap in single quotes. 107 | $strQuery - the query you want to send to Graph. Please see GraphAPI documentation for further into 108 | $ver - what version of Graph to run the query against. (v1.0 / beta) 109 | #> 110 | Function Get-JsonFromGraph { 111 | [cmdletbinding()] 112 | param 113 | ( 114 | [Parameter(Mandatory = $true)] 115 | $strUn, 116 | [Parameter(Mandatory = $true)] 117 | $strPw, 118 | [Parameter(Mandatory = $true)] 119 | $strQuery, 120 | [parameter(mandatory = $true)] [ValidateSet('v1.0', 'beta')] 121 | $ver, 122 | [Parameter(Mandatory = $false)] 123 | $space 124 | 125 | ) 126 | #proxy pass-thru 127 | $webClient = new-object System.Net.WebClient 128 | $webClient.Headers.Add(“user-agent”, “PowerShell Script”) 129 | $webClient.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials 130 | 131 | try { 132 | switch ($space) { 133 | "Intune" { 134 | $header = Get-AuthHeader -un $strUn -pw $strPw -space Intune 135 | break; 136 | } 137 | "AAD" { 138 | $header = Get-AuthHeader -un $strUn -pw $strPw -space AAD 139 | break; 140 | } 141 | } 142 | if ($header) { 143 | #create the URL 144 | $url = "https://graph.microsoft.com/$ver/$strQuery" 145 | 146 | #Invoke the Restful call and display content. 147 | Write-Verbose $url 148 | $query = Invoke-RestMethod -Method Get -Headers $header -Uri $url -ErrorAction STOP 149 | if ($query) { 150 | if ($query.value) { 151 | #multiple results returned. handle it 152 | $query = Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/$ver/$strQuery" -Headers $header 153 | $result = @() 154 | while ($query.'@odata.nextLink') { 155 | Write-Verbose "$($query.value.Count) objects returned from Graph" 156 | $result += $query.value 157 | Write-Verbose "$($result.count) objects in result array" 158 | $query = Invoke-RestMethod -Method Get -Uri $query.'@odata.nextLink' -Headers $header 159 | } 160 | $result += $query.value 161 | Write-Verbose "$($query.value.Count) objects returned from Graph" 162 | Write-Verbose "$($result.count) objects in result array" 163 | return $result 164 | } 165 | else { 166 | #single result returned. handle it. 167 | $query = Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/$ver/$strQuery" -Headers $header 168 | return $query 169 | } 170 | } 171 | else { 172 | $error = @{ 173 | errNumber = 404 174 | errMsg = "No results found. Either there literally is nothing there or your query was malformed." 175 | } 176 | } 177 | throw; 178 | } 179 | else { 180 | $error = @{ 181 | errNumber = 401 182 | errMsg = "Authentication Failed during attempt to create Auth header." 183 | } 184 | throw; 185 | } 186 | } 187 | catch { 188 | return $error 189 | } 190 | } 191 | $objReq = Get-JsonFromGraph -strUn $account.strUn -strPw $account.strPw -strQuery $query -ver $ver -space $space 192 | $objReq | ConvertTo-Json | out-file -encoding ascii -FilePath $res -------------------------------------------------------------------------------- /Invoke-GraphConnector/Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/Invoke-GraphConnector/Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll -------------------------------------------------------------------------------- /Invoke-GraphConnector/Microsoft.IdentityModel.Clients.ActiveDirectory.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/Invoke-GraphConnector/Microsoft.IdentityModel.Clients.ActiveDirectory.dll -------------------------------------------------------------------------------- /Invoke-GraphConnector/appConfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "Accounts": [ 3 | { 4 | "strUn": "testaccount@contoso.com.au", 5 | "strTd": "contoso.com.au", 6 | "strPw": "********" 7 | }, 8 | { 9 | "strUn": "serviceAccount@companyx.it", 10 | "strTd": "companyx.it", 11 | "strPw": "********" 12 | } 13 | ] 14 | } -------------------------------------------------------------------------------- /Invoke-GraphConnector/readme.md: -------------------------------------------------------------------------------- 1 | # Invoke-GraphConnector 2 | Source code for blog post titled "Working with GraphAPI & PowerBI the easy way!" found on https://www.powers-hell.com 3 | 4 | # Notes 5 | The two *.dll files included in this repo originate from the Microsoft AzureAD module. Due to some complexities involed in loading modules into Azure Functions, I had extracted the necessary libraries into this solution. Once modules can be loaded in an easier fashion, these will be removed and the code will be updated. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/.funcignore: -------------------------------------------------------------------------------- 1 | .git* 2 | .vscode 3 | __azurite_db*__.json 4 | __blobstorage__ 5 | __queuestorage__ 6 | local.settings.json 7 | test -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Azure Functions artifacts 3 | bin 4 | obj 5 | appsettings.json 6 | local.settings.json 7 | 8 | # Azurite artifacts 9 | __blobstorage__ 10 | __queuestorage__ 11 | __azurite_db*__.json -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/HttpTrigger1/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "bindings": [ 3 | { 4 | "authLevel": "function", 5 | "type": "httpTrigger", 6 | "direction": "in", 7 | "name": "Request", 8 | "methods": [ 9 | "get", 10 | "post" 11 | ] 12 | }, 13 | { 14 | "type": "http", 15 | "direction": "out", 16 | "name": "Response" 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/HttpTrigger1/run.ps1: -------------------------------------------------------------------------------- 1 | using namespace System.Net 2 | 3 | # Input bindings are passed in via param block. 4 | param($Request, $TriggerMetadata) 5 | 6 | #region auth 7 | if ($env:MSI_SECRET) { $token = (Get-AzAccessToken -resourceUrl "https://graph.microsoft.com/").Token } 8 | else { 9 | Disable-AzContextAutosave -Scope Process | Out-Null 10 | $cred = New-Object System.Management.Automation.PSCredential $env:appId, ($env:secret | ConvertTo-SecureString -AsPlainText -Force) 11 | Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $env:tenantId 12 | $token = (Get-AzAccessToken -resourceUrl "https://graph.microsoft.com/").Token 13 | } 14 | $authHeader = @{ Authorization = "Bearer $token" } 15 | #endregion 16 | #region main process 17 | try { 18 | $restParams = @{ 19 | Method = 'Get' 20 | Uri = 'https://graph.microsoft.com/beta/devices' 21 | Headers = $authHeader 22 | ContentType = 'application/json' 23 | } 24 | $restCall = Invoke-RestMethod @restParams 25 | Write-Output "Devices Found: $($restCall.value.count)" 26 | $resp = $restCall.value | ConvertTo-Json -Depth 100 27 | $statusCode = [HttpStatusCode]::OK 28 | $body = $resp 29 | } 30 | catch { 31 | Write-Output $_.Exception.Message 32 | $statusCode = [HttpStatusCode]::BadRequest 33 | $body = $_.Exception.Message 34 | } 35 | 36 | Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 37 | StatusCode = $statusCode 38 | Body = $body 39 | }) 40 | #endregion -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/HttpTrigger1/sample.dat: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Azure" 3 | } 4 | -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | }, 11 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[4.*, 5.0.0)" 14 | }, 15 | "managedDependency": { 16 | "enabled": true 17 | } 18 | } -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/profile.ps1: -------------------------------------------------------------------------------- 1 | # Azure Functions profile.ps1 2 | # 3 | # This profile.ps1 will get executed every "cold start" of your Function App. 4 | # "cold start" occurs when: 5 | # 6 | # * A Function App starts up for the very first time 7 | # * A Function App starts up after being de-allocated due to inactivity 8 | # 9 | # You can define helper functions, run commands, or specify environment variables 10 | # NOTE: any variables defined that are not environment variables will get reset after the first execution 11 | 12 | # Authenticate with Azure PowerShell using MSI. 13 | # Remove this if you are not planning on using MSI or Azure PowerShell. 14 | if ($env:MSI_SECRET) { 15 | Disable-AzContextAutosave -Scope Process | Out-Null 16 | Connect-AzAccount -Identity 17 | } 18 | 19 | # Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell. 20 | # Enable-AzureRmAlias 21 | 22 | # You can also define functions or aliases that can be referenced in any of your PowerShell functions. 23 | -------------------------------------------------------------------------------- /MSI-AzFunction-Demo/requirements.psd1: -------------------------------------------------------------------------------- 1 | # This file enables modules to be automatically managed by the Functions service. 2 | # See https://aka.ms/functionsmanageddependency for additional information. 3 | # 4 | @{ 5 | # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. Uncomment the next line and replace the MAJOR_VERSION, e.g., 'Az' = '5.*' 6 | 'Az.Accounts' = '4.*' 7 | } -------------------------------------------------------------------------------- /New-PolicyFromTemplate/New-PolicyFromTemplate.ps1: -------------------------------------------------------------------------------- 1 | [cmdletbinding()] 2 | param ( 3 | [string]$tenantId 4 | ) 5 | $script:tick = [char]0x221a 6 | $baseUrl = "https://graph.microsoft.com/beta/deviceManagement" 7 | try { 8 | #region auth 9 | $auth = Get-MsalToken -ClientId 'd1ddf0e4-d672-4dae-b554-9d5bdfd93547' -Interactive -TenantId $tenantId -DeviceCode 10 | $authHeader = @{Authorization = "Bearer $($auth.AccessToken)"} 11 | #endregion auth 12 | #region get BitLocker template from graph 13 | Write-Host "Grabbing BitLocker template data.." -NoNewline -ForegroundColor Yellow 14 | $bitlocker = Invoke-RestMethod -Method Get -Uri "$baseUrl/templates?`$filter=startswith(displayName,'BitLocker')" -Headers $authHeader 15 | Write-Host "$script:tick ($($bitlocker.value.id))" -ForegroundColor Green 16 | #endregion get BitLocker template from graph 17 | #region new template instance 18 | Write-Host "Creating new template instance.." -NoNewline -ForegroundColor Yellow 19 | $request = @{ 20 | displayName = "Win10_BitLocker_Example" 21 | description = "Win10 BitLocker Example for Powers-Hell.com" 22 | templateId = $bitlocker.value.id 23 | } | ConvertTo-Json 24 | $instance = Invoke-RestMethod -Method Post -Uri "$baseUrl/templates/$($bitlocker.value.id)/createInstance" -Headers $authHeader -ContentType 'Application/Json' -body $request 25 | Write-Host "$script:tick ($($instance.id))" -ForegroundColor Green 26 | #endregion new template instance 27 | #region update instance settings 28 | Write-Host "Updating instance with intent settings.." -NoNewline -ForegroundColor Yellow 29 | $definitionBase = 'deviceConfiguration--windows10EndpointProtectionConfiguration_' 30 | $request = @( 31 | @{ 32 | "settings" = @( 33 | @{ 34 | "@odata.type" = "#microsoft.graph.deviceManagementBooleanSettingInstance" 35 | "definitionId" = "$($definitionBase)bitLockerEncryptDevice" 36 | "value" = $true 37 | } 38 | @{ 39 | "@odata.type" = "#microsoft.graph.deviceManagementBooleanSettingInstance" 40 | "definitionId" = "$($definitionBase)bitLockerEnableStorageCardEncryptionOnMobile" 41 | "value" = $true 42 | } 43 | @{ 44 | "@odata.type" = "#microsoft.graph.deviceManagementBooleanSettingInstance" 45 | "definitionId" = "$($definitionBase)bitLockerDisableWarningForOtherDiskEncryption" 46 | "value" = $true 47 | } 48 | @{ 49 | "@odata.type" = "#microsoft.graph.deviceManagementBooleanSettingInstance" 50 | "definitionId" = "$($definitionBase)bitLockerAllowStandardUserEncryption" 51 | "value" = $true 52 | } 53 | @{ 54 | "@odata.type" = "#microsoft.graph.deviceManagementStringSettingInstance" 55 | "definitionId" = "$($definitionBase)bitLockerRecoveryPasswordRotation" 56 | "value" = "enabledForAzureAd" 57 | } 58 | ) 59 | } 60 | ) | ConvertTo-Json 61 | Invoke-RestMethod -Method Post -Uri "$baseUrl/intents/$($instance.id)/updateSettings" -ContentType 'Application/JSON' -Headers $authHeader -Body $request | Out-Null 62 | Write-Host $script:tick -ForegroundColor Green 63 | #endregion update instance settings 64 | } 65 | catch { 66 | Write-Warning $_ 67 | } -------------------------------------------------------------------------------- /New-PolicyFromTemplate/restExamples/policyTemplates.rest: -------------------------------------------------------------------------------- 1 | ### variables 2 | @resourceURL = htts://graph.microsoft.com 3 | @applicationId = 00000000-0000-0000-0000-0000v00000000 4 | @upn = user@contoso.com 5 | @password = superSecretPassword 6 | @contentType = application/json 7 | @authorization = Bearer {{auth.response.body.access_token}} 8 | @baseUrl = https://graph.microsoft.com/beta/deviceManagement 9 | 10 | ### Authenticate to Graph 11 | // @name auth 12 | GET https://login.microsoftonline.com/Common/oauth2/token HTTP/1.1 13 | 14 | resource={{resourceURL}} 15 | &client_id={{applicationId}} 16 | &grant_type=password 17 | &username={{upn}} 18 | &scope=openid 19 | &password={{password}} 20 | 21 | ### List all available templates 22 | // @name templates 23 | GET {{baseUrl}}/templates HTTP/1.1 24 | Content-Type: {{contentType}} 25 | Authorization: {{authorization}} 26 | 27 | ### Select BitLocker template 28 | // @name bitlocker 29 | GET {{baseUrl}}/templates?$filter=startswith(displayName,'BitLocker') HTTP/1.1 30 | Content-Type: {{contentType}} 31 | Authorization: {{authorization}} 32 | 33 | ### Create new BitLocker Instance 34 | // @name newBitlocker 35 | POST {{baseUrl}}/templates/{{bitlocker.response.body.value[0].id}}/createInstance HTTP/1.1 36 | Content-Type: {{contentType}} 37 | Authorization: {{authorization}} 38 | 39 | { 40 | "displayName": "Win10_BitLocker_Test", 41 | "description": "Win10_BitLocker_Test", 42 | "templateId": "{{bitlocker.response.body.value[0].id}}" 43 | } 44 | 45 | ### Update instance settings 46 | @definitionBase = deviceConfiguration--windows10EndpointProtectionConfiguration_ 47 | POST {{baseUrl}}/intents/{{newBitlocker.response.body.id}}/updateSettings HTTP/1.1 48 | Content-Type: {{contentType}} 49 | Authorization: {{authorization}} 50 | 51 | { 52 | "settings": [{ 53 | "@odata.type": "#microsoft.graph.deviceManagementBooleanSettingInstance", 54 | "definitionId": "{{definitionBase}}bitLockerEncryptDevice", 55 | "value": true 56 | }, 57 | { 58 | "@odata.type": "#microsoft.graph.deviceManagementBooleanSettingInstance", 59 | "definitionId": "{{definitionBase}}bitLockerEnableStorageCardEncryptionOnMobile", 60 | "value": true 61 | }, 62 | { 63 | "@odata.type": "#microsoft.graph.deviceManagementBooleanSettingInstance", 64 | "definitionId": "{{definitionBase}}bitLockerDisableWarningForOtherDiskEncryption", 65 | "value": true 66 | }, 67 | { 68 | "@odata.type": "#microsoft.graph.deviceManagementBooleanSettingInstance", 69 | "definitionId": "{{definitionBase}}bitLockerAllowStandardUserEncryption", 70 | "value": true 71 | }, 72 | { 73 | "@odata.type": "#microsoft.graph.deviceManagementStringSettingInstance", 74 | "definitionId": "{{definitionBase}}bitLockerRecoveryPasswordRotation", 75 | "value": "notConfigured" 76 | }] 77 | } -------------------------------------------------------------------------------- /OMA-URI_CheatSheet/OMA-URI_CheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/OMA-URI_CheatSheet/OMA-URI_CheatSheet.pdf -------------------------------------------------------------------------------- /PSConfAsia/Get-WordPressPostSummary.ps1: -------------------------------------------------------------------------------- 1 | function Get-WordPressPostSummary { 2 | [CmdletBinding()] 3 | param ( 4 | [string[]]$url 5 | ) 6 | try { 7 | $result = @() 8 | foreach ($blog in $url) { 9 | $hostName = $blog -replace '(^http:\/\/)|(\/$)', '' 10 | try { 11 | $iwr = Invoke-WebRequest -Method Get -UseBasicParsing ` 12 | -Uri "http://$($hostName)/wp-json/wp/v2/posts" 13 | 14 | } 15 | catch { 16 | $iwr = Invoke-WebRequest -Method Get -UseBasicParsing ` 17 | -Uri "http://$($hostName)/?rest_route=/wp/v2/posts" 18 | } 19 | if ($iwr.StatusCode -eq 200) { 20 | $jsonContent = $iwr.Content | ConvertFrom-Json 21 | foreach ($post in $jsonContent) { 22 | $result += [PSCustomObject]@{ 23 | Date = get-date $($post.date) 24 | Link = [System.Web.HttpUtility]::HtmlDecode($post.link) 25 | Title = [System.Web.HttpUtility]::HtmlDecode($post.title.rendered) 26 | Excerpt = [System.Web.HttpUtility]::HtmlDecode($post.excerpt.rendered) ` 27 | -replace '\<\/?.*?\>', "" 28 | } 29 | } 30 | } 31 | } 32 | if ($result) { 33 | return $result | Sort-Object -Property Date -Descending 34 | } 35 | else { 36 | Throw $iwr.StatusCode 37 | } 38 | } 39 | catch { 40 | Write-Warning $_.Exception.Message 41 | } 42 | } 43 | Get-WordPressPostSummary -url "blog.vigilant.it", "powers-hell.com", "steven.hosking.com.au" 44 | -------------------------------------------------------------------------------- /PowerBI-GraphAuthentication/PowerBI_Graph_Authentication.pbit: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/PowerBI-GraphAuthentication/PowerBI_Graph_Authentication.pbit -------------------------------------------------------------------------------- /PowerBI-GraphAuthentication/PowerBI_Graph_Authentication_Updated.pbit: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tabs-not-spaces/CodeDump/e5ab88d997b1e4232f9e2483e5a046b9517eb0f6/PowerBI-GraphAuthentication/PowerBI_Graph_Authentication_Updated.pbit -------------------------------------------------------------------------------- /Publish-ScriptToIntune/Publish-ScriptToIntune.ps1: -------------------------------------------------------------------------------- 1 | #requires -module msal.ps 2 | function Publish-ScriptToIntune { 3 | [CmdletBinding()] 4 | param ( 5 | [Parameter(Mandatory = $true)] 6 | [System.IO.FileInfo]$ScriptFilePath, 7 | 8 | [Parameter(Mandatory = $true)] 9 | [string]$DisplayName, 10 | 11 | [Parameter(Mandatory = $true)] 12 | [string]$Description, 13 | 14 | [Parameter(Mandatory = $false)] 15 | [ValidateSet("System", "User")] 16 | [string]$RunAsAccount = "System", 17 | 18 | [Parameter(Mandatory = $false)] 19 | [boolean]$EnforceSignatureCheck, 20 | 21 | [Parameter(Mandatory = $false)] 22 | [boolean]$RunAs32Bit 23 | 24 | ) 25 | try { 26 | $script:tick = [char]0x221a 27 | $errorMsg = $null 28 | #region authenticate to Graph 29 | if ($PSVersionTable.PSEdition -ne "Core") { 30 | $auth = Get-MsalToken -ClientId "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Interactive 31 | } 32 | else { 33 | $auth = Get-MsalToken -ClientId "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" -DeviceCode 34 | } 35 | if (!($auth)) { 36 | throw "Authentication failed." 37 | } 38 | $script:authToken = @{ 39 | Authorization = $auth.CreateAuthorizationHeader() 40 | } 41 | #endregion 42 | #region encode the script content to base64 43 | $scriptContent = Get-Content "$ScriptFilePath" -Raw 44 | $encodedScriptContent = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$scriptContent")) 45 | #endregion 46 | #region build the request body 47 | $postBody = [PSCustomObject]@{ 48 | displayName = $DisplayName 49 | description = $Description 50 | enforceSignatureCheck = $EnforceSignatureCheck 51 | fileName = $ScriptFilePath.Name 52 | runAs32Bit = $RunAs32Bit 53 | runAsAccount = $RunAsAccount 54 | scriptContent = $encodedScriptContent 55 | } | ConvertTo-Json -Depth 10 56 | #endregion 57 | Write-Host "`nPosting script content to Intune: " -NoNewline -ForegroundColor Cyan 58 | #region post the request 59 | $postParams = @{ 60 | Method = "Post" 61 | Uri = "https://graph.microsoft.com/Beta/deviceManagement/deviceManagementScripts" 62 | Headers = $script:authToken 63 | Body = $postBody 64 | ContentType = "Application/Json" 65 | } 66 | if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) { 67 | Write-Host "`n" 68 | } 69 | $res = Invoke-RestMethod @postParams 70 | #endregion 71 | } 72 | catch { 73 | $errorMsg = $_.Exception.Message 74 | } 75 | finally { 76 | if ($auth) { 77 | if ($errorMsg) { 78 | Write-Host "X`n" -ForegroundColor Red 79 | Write-Warning $errorMsg 80 | } 81 | else { 82 | if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) { 83 | $res 84 | } 85 | Write-Host "$script:tick Script published to Intune with ID $($res.id)" -ForegroundColor Green 86 | } 87 | } 88 | } 89 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodeDump 2 | things that help me. might help others. 3 | -------------------------------------------------------------------------------- /Registry-Configuration/Registry-Configuration.ps1: -------------------------------------------------------------------------------- 1 | #region Config 2 | $AppName = "Registry-Modifications" 3 | $client = "MegaCorp" 4 | $logPath = "$env:ProgramData\$client\logs" 5 | $logFile = "$logPath\$appName.log" 6 | #region Keys 7 | $hkcuKeys = @( 8 | [PSCustomObject]@{ 9 | Guid = "{fc996e2d-4931-42fe-8276-fbfa1967c008}" 10 | Name = "PropertyA" 11 | Type = "DWord" 12 | Value = 1 13 | Path = "Software\Path\To\Registry\Key" 14 | } 15 | [PSCustomObject]@{ 16 | Guid = "{b94177b7-31e5-4499-94c1-0017425f0f59}" 17 | Name = "propertyB" 18 | Type = "DWord" 19 | Value = 1 20 | Path = "Software\Path\To\Registry\Key" 21 | } 22 | ) 23 | $hklmKeys = @( 24 | [PSCustomObject]@{ 25 | Path = "HKLM:\Software\Path\To\Registry\Key" 26 | Name = "PropertyA" 27 | Type = "DWORD" 28 | value = "1" 29 | } 30 | [PSCustomObject]@{ 31 | Path = "HKLM:\Software\Path\To\Registry\Key" 32 | Name = "PropertyB" 33 | Type = "DWORD" 34 | value = "1" 35 | } 36 | ) 37 | #endregion 38 | #endregion 39 | #region Functions 40 | function Set-RegistryValueForAllUsers { 41 | <# 42 | .SYNOPSIS 43 | This function uses Active Setup to create a "seeder" key which creates or modifies a user-based registry value 44 | for all users on a computer. If the key path doesn't exist to the value, it will automatically create the key and add the value. 45 | .EXAMPLE 46 | PS> Set-RegistryValueForAllUsers -RegistryInstance @{'Name' = 'Setting'; 'Type' = 'String'; 'Value' = 'someval'; 'Path' = 'SOFTWARE\Microsoft\Windows\Something'} 47 | This example would modify the string registry value 'Type' in the path 'SOFTWARE\Microsoft\Windows\Something' to 'someval' 48 | for every user registry hive. 49 | .PARAMETER RegistryInstance 50 | A hash table containing key names of 'Name' designating the registry value name, 'Type' to designate the type 51 | of registry value which can be 'String,Binary,Dword,ExpandString or MultiString', 'Value' which is the value itself of the 52 | registry value and 'Path' designating the parent registry key the registry value is in. 53 | #> 54 | [CmdletBinding()] 55 | param ( 56 | [Parameter(Mandatory = $true)] 57 | $RegistryInstance 58 | ) 59 | try { 60 | New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS | Out-Null 61 | 62 | ## Change the registry values for the currently logged on user. Each logged on user SID is under HKEY_USERS 63 | $LoggedOnSids = $(Get-ChildItem HKU: | Where-Object { $_.Name -match 'S-\d-\d+-(\d+-){1,14}\d+$' } | ForEach-Object { $_.Name }) 64 | Write-Verbose "Found $($LoggedOnSids.Count) logged on user SIDs" 65 | foreach ($sid in $LoggedOnSids) { 66 | Write-Host "Loading the user registry hive for the logged on SID $sid" -ForegroundColor Green 67 | foreach ($instance in $RegistryInstance) { 68 | ## Create the key path if it doesn't exist 69 | if (!(Test-Path "HKU:\$sid\$($instance.Path)")) { 70 | New-Item -Path "HKU:\$sid\$($instance.Path | Split-Path -Parent)" -Name ($instance.Path | Split-Path -Leaf) -Force 71 | } 72 | ## Create (or modify) the value specified in the param 73 | Set-ItemProperty -Path "HKU:\$sid\$($instance.Path)" -Name $instance.Name -Value $instance.Value -Type $instance.Type -Force 74 | } 75 | } 76 | 77 | ## Create the Active Setup registry key so that the reg add cmd will get ran for each user 78 | ## logging into the machine. 79 | ## http://www.itninja.com/blog/view/an-active-setup-primer 80 | Write-Host "Setting Active Setup registry value to apply to all other users" -ForegroundColor Green 81 | foreach ($instance in $RegistryInstance) { 82 | ## Generate a unique value (usually a GUID) to use for Active Setup 83 | $Guid = $instance.Guid 84 | $ActiveSetupRegParentPath = 'HKLM:\Software\Microsoft\Active Setup\Installed Components' 85 | ## Create the GUID registry key under the Active Setup key 86 | $ActiveSetupRegPath = "HKLM:\Software\Microsoft\Active Setup\Installed Components\$Guid" 87 | if (!(Test-Path -Path "$ActiveSetupRegPath")) { 88 | New-Item -Path $ActiveSetupRegParentPath -Name $Guid -Force 89 | } 90 | Write-Verbose "Using registry path '$ActiveSetupRegPath'" 91 | ## Convert the registry value type to one that reg.exe can understand. This will be the 92 | ## type of value that's created for the value we want to set for all users 93 | switch ($instance.Type) { 94 | 'String' { 95 | $RegValueType = 'REG_SZ' 96 | } 97 | 'Dword' { 98 | $RegValueType = 'REG_DWORD' 99 | } 100 | 'Binary' { 101 | $RegValueType = 'REG_BINARY' 102 | } 103 | 'ExpandString' { 104 | $RegValueType = 'REG_EXPAND_SZ' 105 | } 106 | 'MultiString' { 107 | $RegValueType = 'REG_MULTI_SZ' 108 | } 109 | default { 110 | throw "Registry type '$($instance.Type)' not recognized" 111 | } 112 | } 113 | 114 | ## Build the registry value to use for Active Setup which is the command to create the registry value in all user hives 115 | $ActiveSetupValue = "reg add `"{0}`" /v {1} /t {2} /d {3} /f" -f "HKCU\$($instance.Path)", $instance.Name, $RegValueType, $instance.Value 116 | Write-Verbose -Message "Active setup value is '$ActiveSetupValue'" 117 | ## Create the necessary Active Setup registry values 118 | Set-ItemProperty -Path $ActiveSetupRegPath -Name '(Default)' -Value 'Active Setup Test' -Force 119 | Set-ItemProperty -Path $ActiveSetupRegPath -Name 'Version' -Value '1' -Force 120 | Set-ItemProperty -Path $ActiveSetupRegPath -Name 'StubPath' -Value $ActiveSetupValue -Force 121 | } 122 | } 123 | catch { 124 | Throw -Message $_.Exception.Message 125 | } 126 | } 127 | #endregion 128 | #region Logging 129 | if (!(Test-Path -Path $logPath)) { 130 | New-Item -Path $logPath -ItemType Directory -Force | Out-Null 131 | } 132 | $errorOccurred = $false 133 | Start-Transcript -Path $logFile -ErrorAction SilentlyContinue -Force 134 | #endregion 135 | #region Process 136 | try { 137 | if ($hkcuKeys) { 138 | Write-Host "Seting HKCU registry keys.." -ForegroundColor Green 139 | foreach ($key in $hkcuKeys) { 140 | Set-RegistryValueForAllUsers -RegistryInstance $hkcuKeys 141 | Write-Host "========" 142 | } 143 | } 144 | foreach ($key in $hklmKeys) { 145 | Write-Host "Setting HKLM registry keys.." -ForegroundColor Green 146 | if (!(Test-Path $($key.Path))) { 147 | Write-Host "Registry path not found. Creating now." -ForegroundColor Green 148 | New-Item -Path $($key.Path) -Force | Out-Null 149 | Write-Host "Creating item property." -ForegroundColor Green 150 | New-ItemProperty -Path $($key.Path) -Name $($key.Name) -Value $($key.value) -PropertyType DWORD -Force | Out-Null 151 | } 152 | else { 153 | Write-Host "Registry path found." -ForegroundColor Green 154 | Write-Host "Creating item property." -ForegroundColor Green 155 | New-ItemProperty -Path $($key.Path) -Name $($key.Name) -Value $($key.value) -PropertyType DWORD -Force | Out-Null 156 | } 157 | } 158 | } 159 | catch { 160 | $errorOccurred = $_.Exception.Message 161 | } 162 | finally { 163 | if ($errorOccurred) { 164 | Write-Warning $errorOccurred 165 | Stop-Transcript 166 | throw $errorOccurred 167 | } 168 | else { 169 | Write-Host "Script completed successfully.." 170 | Stop-Transcript -ErrorAction SilentlyContinue 171 | } 172 | } 173 | #endregion 174 | -------------------------------------------------------------------------------- /Reset-SidecarScript/Reset-SideCarScript.ps1: -------------------------------------------------------------------------------- 1 | if (!(Get-Module -Name MSAL.PS -ListAvailable -ErrorAction SilentlyContinue)) { 2 | Install-Module -Name MSAL.PS -Scope CurrentUser -Force -AcceptLicense 3 | } 4 | $clientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" # well known Intune application Id 5 | $auth = Get-MsalToken -ClientId $clientId -deviceCode #deviceCode requires interaction and solves MFA challenges 6 | $token = @{ Authorization = $auth.CreateAuthorizationHeader() } 7 | 8 | $graph = "https://graph.microsoft.com" 9 | $deviceProps = (invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/v1.0/devices?`$filter=DisplayName eq '$env:ComputerName'" -Headers $token).value 10 | $owner = (Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/v1.0/devices/$($deviceProps.id)/registeredOwners" -Headers $token).value 11 | $sidecarScripts = (Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts" -Headers $token).value 12 | $deviceScriptStatus = @() 13 | foreach ($script in $sidecarScripts) { 14 | $tmpItem = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension\Policies\$($owner.id)\$($script.id)" -ErrorAction SilentlyContinue 15 | if ($tmpItem) { 16 | $tmpObj = [PSCustomObject]@{ 17 | displayName = $script.displayName 18 | fileName = $script.fileName 19 | Result = $tmpItem.Result 20 | id = $script.id 21 | psPath = $tmpItem.PSPath 22 | } 23 | $deviceScriptStatus += $tmpObj 24 | } 25 | } 26 | $intuneScriptToRerun = $deviceScriptStatus | Select-Object displayName,fileName,Result,id | Out-GridView -Title "Intune Script Configuration" -PassThru 27 | 28 | foreach ($item in $intuneScriptToRerun){ 29 | $itemPath = ($deviceScriptStatus | Where-Object {$_.displayName -eq $item.displayName}).psPath 30 | Remove-Item $itemPath -Force 31 | } 32 | Get-Service -Name IntuneManagementExtension | Restart-Service 33 | -------------------------------------------------------------------------------- /Reset-SidecarScript/readme.md: -------------------------------------------------------------------------------- 1 | # Reset-SideCarScript 2 | Source code for blog post titled "How to force Intune configuration script to re-run" found on https://www.powers-hell.com -------------------------------------------------------------------------------- /ScheduledZoomPackager/Get-ZoomUpdate.ps1: -------------------------------------------------------------------------------- 1 | function Get-ZoomUpdate { 2 | [cmdletbinding()] 3 | param ( 4 | [parameter(Mandatory = $false)] 5 | [string]$downloadPath 6 | ) 7 | $content = Invoke-WebRequest -Method Get -Uri "https://support.zoom.us/hc/en-us/articles/201361953" -ContentType 'Application/Json' | Select-Object -ExpandProperty content 8 | $split = (($content.Split("Current Release")[1].Split("Download Type: Manual")[0] -replace '
',"`n") -replace '<[^>]+>',' ').trim().Split("`n") 9 | $val = @{ 10 | VersionDate = $split[0].Split("version")[0].Trim().TrimEnd() 11 | VersionNumber = $split[0].Split("version")[1].Trim().TrimEnd() 12 | DownloadType = $split[1].Split("Download type:")[-1].Trim().TrimEnd() 13 | DownloadLink = [uri]"https://zoom.us/client/latest/ZoomInstallerFull.msi" 14 | } 15 | if ($downloadPath) { 16 | if (!(Test-Path $downloadPath -ErrorAction SilentlyContinue)) { 17 | New-Item $downloadPath -ItemType Directory -Force | Out-Null 18 | } 19 | $fileName = '{0}-{1}.msi' -f $($val.DownloadLink.Segments[-1].Split('.msi')[0]), $($val.VersionNumber.Split('(')[0].TrimEnd()) 20 | $val.InstallationMedia = "$downloadPath\$fileName" 21 | Invoke-WebRequest -Method Get -Uri $val.DownloadLink -OutFile "$($val.InstallationMedia)" 22 | $val.ProductCode = (Get-MSIProperty -Path "$($val.InstallationMedia)"-Property ProductCode).value 23 | $val.ProductVersion = (Get-MSIProperty -Path "$($val.InstallationMedia)" -Property ProductVersion).value 24 | $val.FileSize = "$([math]::Round(((Get-ChildItem "$($val.InstallationMedia)").Length / 1mb)))Mb" 25 | } 26 | $res = New-Object PSCustomObject -Property $val 27 | return $res 28 | } -------------------------------------------------------------------------------- /Send-IntuneLogsToFlow/Send-IntuneLogsToFlow.ps1: -------------------------------------------------------------------------------- 1 | #region Function 2 | function Send-IntuneLogsToFlow { 3 | param ( 4 | $inputObject, 5 | $metaData 6 | ) 7 | $Uri = "https://azure.flow.url.com"; 8 | try { 9 | $jsonMetaData = $metaData | ConvertTo-Json -Compress 10 | if (Test-Path $inputObject) { 11 | $fileBytes = [System.IO.File]::ReadAllBytes("$inputObject") 12 | $fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes) 13 | } 14 | else { 15 | throw "Error accessing input object: $inputObject" 16 | } 17 | $boundary = [System.Guid]::NewGuid().ToString() 18 | $lf = "`r`n" 19 | $bodyLines = ( 20 | "--$boundary", 21 | "Content-Disposition: form-data; name=`"$(split-path $inputObject -leaf)`"; filename=`"$(split-path $inputObject -leaf)`"", 22 | "Content-Type: application/octet-stream$lf", 23 | $fileEnc, 24 | "--$boundary", 25 | "Content-Disposition: form-data; name=`"MetaData`"", 26 | "Content-Type: application/json$lf", 27 | $jsonMetaData, 28 | "--$boundary--$lf" 29 | ) -join $lf 30 | $req = Invoke-WebRequest -Uri $uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines 31 | return $req 32 | } 33 | catch { 34 | Write-Warning $_.Exception.Message 35 | } 36 | } 37 | #endregion 38 | #region Process block 39 | $logFile = "Path\To\Logfile.log" 40 | $metaData = [PSCustomObject]@{ 41 | hostName = $env:COMPUTERNAME 42 | clientName = "Contoso" 43 | appName = "ApplicationName" 44 | logFileName = "$env:COMPUTERNAME`_$(Split-Path $logFile -leaf)" 45 | } 46 | #endregion -------------------------------------------------------------------------------- /Set-RegistryValueForAllUsers/Set-RegistryValueForAllUsers.ps1: -------------------------------------------------------------------------------- 1 | function Set-RegistryValueForAllUsers { 2 | <# 3 | .SYNOPSIS 4 | This function uses Active Setup to create a "seeder" key which creates or modifies a user-based registry value 5 | for all users on a computer. If the key path doesn't exist to the value, it will automatically create the key and add the value. 6 | .EXAMPLE 7 | PS> Set-RegistryValueForAllUsers -RegistryInstance @{'Name' = 'Setting'; 'Type' = 'String'; 'Value' = 'someval'; 'Path' = 'SOFTWARE\Microsoft\Windows\Something'} 8 | 9 | This example would modify the string registry value 'Setting' in the path 'SOFTWARE\Microsoft\Windows\Something' to 'someval' 10 | for every user registry hive. 11 | .PARAMETER RegistryInstance 12 | A hash table containing key names of 'Name' designating the registry value name, 'Type' to designate the type 13 | of registry value which can be 'String,Binary,Dword,ExpandString or MultiString', 'Value' which is the value itself of the 14 | registry value and 'Path' designating the parent registry key the registry value is in. 15 | #> 16 | [CmdletBinding()] 17 | param ( 18 | [Parameter(Mandatory = $true)] 19 | [hashtable[]]$RegistryInstance 20 | ) 21 | try { 22 | New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS | Out-Null 23 | 24 | ## Change the registry values for the currently logged on user. Each logged on user SID is under HKEY_USERS 25 | $LoggedOnSids = $(Get-ChildItem HKU: | Where-Object { $_.Name -match 'S-\d-\d+-(\d+-){1,14}\d+$' } | foreach-object { $_.Name }) 26 | Write-Verbose "Found $($LoggedOnSids.Count) logged on user SIDs" 27 | foreach ($sid in $LoggedOnSids) { 28 | Write-Verbose -Message "Loading the user registry hive for the logged on SID $sid" 29 | foreach ($instance in $RegistryInstance) { 30 | ## Create the key path if it doesn't exist 31 | if (!(Test-Path "HKU:\$sid\$($instance.Path)")) { 32 | New-Item -Path "HKU:\$sid\$($instance.Path | Split-Path -Parent)" -Name ($instance.Path | Split-Path -Leaf) -Force | Out-Null 33 | } 34 | ## Create (or modify) the value specified in the param 35 | Set-ItemProperty -Path "HKU:\$sid\$($instance.Path)" -Name $instance.Name -Value $instance.Value -Type $instance.Type -Force 36 | } 37 | } 38 | 39 | ## Create the Active Setup registry key so that the reg add cmd will get ran for each user 40 | ## logging into the machine. 41 | ## http://www.itninja.com/blog/view/an-active-setup-primer 42 | Write-Verbose "Setting Active Setup registry value to apply to all other users" 43 | foreach ($instance in $RegistryInstance) { 44 | ## Generate a unique value (usually a GUID) to use for Active Setup 45 | $Guid = [guid]::NewGuid().Guid 46 | $ActiveSetupRegParentPath = 'HKLM:\Software\Microsoft\Active Setup\Installed Components' 47 | ## Create the GUID registry key under the Active Setup key 48 | New-Item -Path $ActiveSetupRegParentPath -Name $Guid -Force | Out-Null 49 | $ActiveSetupRegPath = "HKLM:\Software\Microsoft\Active Setup\Installed Components\$Guid" 50 | Write-Verbose "Using registry path '$ActiveSetupRegPath'" 51 | 52 | ## Convert the registry value type to one that reg.exe can understand. This will be the 53 | ## type of value that's created for the value we want to set for all users 54 | switch ($instance.Type) { 55 | 'String' { 56 | $RegValueType = 'REG_SZ' 57 | } 58 | 'Dword' { 59 | $RegValueType = 'REG_DWORD' 60 | } 61 | 'Binary' { 62 | $RegValueType = 'REG_BINARY' 63 | } 64 | 'ExpandString' { 65 | $RegValueType = 'REG_EXPAND_SZ' 66 | } 67 | 'MultiString' { 68 | $RegValueType = 'REG_MULTI_SZ' 69 | } 70 | default { 71 | throw "Registry type '$($instance.Type)' not recognized" 72 | } 73 | } 74 | 75 | ## Build the registry value to use for Active Setup which is the command to create the registry value in all user hives 76 | $ActiveSetupValue = "reg add `"{0}`" /v {1} /t {2} /d {3} /f" -f "HKCU\$($instance.Path)", $instance.Name, $RegValueType, $instance.Value 77 | Write-Verbose -Message "Active setup value is '$ActiveSetupValue'" 78 | ## Create the necessary Active Setup registry values 79 | Set-ItemProperty -Path $ActiveSetupRegPath -Name '(Default)' -Value 'Active Setup Test' -Force 80 | Set-ItemProperty -Path $ActiveSetupRegPath -Name 'Version' -Value '1' -Force 81 | Set-ItemProperty -Path $ActiveSetupRegPath -Name 'StubPath' -Value $ActiveSetupValue -Force 82 | } 83 | } 84 | catch { 85 | Write-Warning -Message $_.Exception.Message 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Set-Timezone/Set-TimezoneFromLocation.ps1: -------------------------------------------------------------------------------- 1 | $apiKey = '000000000000000000000000000000' #use a subscription key from your Azure Maps Account 2 | function ConvertFrom-IanaName { 3 | [cmdletbinding()] 4 | param ( 5 | [parameter(Mandatory = $true)] 6 | [string]$apiKey, 7 | [parameter(Mandatory = $true, ValueFromPipeline)] 8 | [string]$IanaName 9 | ) 10 | $tzList = Invoke-RestMethod -Method Get -Uri "https://atlas.microsoft.com/timezone/enumWindows/json?subscription-key=$apiKey&api-version=1.0" -ContentType 'Application/Json' 11 | $result = $tzList | Where-Object { $IanaName -in $_.IanaIds } 12 | return $result 13 | } 14 | 15 | try { 16 | Add-Type -AssemblyName System.Device 17 | $gw = New-Object System.Device.Location.GeoCoordinateWatcher 18 | $gw.Start() 19 | while (($gw.Status -ne 'Ready') -and ($gw.Permission -ne 'Denied')) { 20 | Start-Sleep -Milliseconds 100 #Wait for discovery. 21 | } 22 | 23 | if ($gw.Permission -eq 'Denied') { 24 | Throw 'Access Denied for Location Information' 25 | } 26 | else { 27 | $baseUri = "https://atlas.microsoft.com/timezone" 28 | $locData = Invoke-RestMethod -Method Get -Uri "$baseUri/byCoordinates/json?subscription-key=$apiKey&api-version=1.0&query=$($gw.Position.Location.Latitude),$($gw.Position.Location.Longitude)" -ContentType 'Application/Json' 29 | $timezone = ConvertFrom-IanaName -apiKey $apiKey -IanaName $locData.TimeZones.id 30 | Write-Host "Setting timezone to $($timezone.WindowsId)" 31 | Set-Timezone -Id $timezone.WindowsId 32 | } 33 | } 34 | catch { 35 | Write-Warning $_.Exception.Message 36 | } 37 | finally { 38 | $gw.Dispose() 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Sync-SharepointFolder/Sync-SharepointFolder.ps1: -------------------------------------------------------------------------------- 1 | #region Functions 2 | function Sync-SharepointLocation { 3 | param ( 4 | [guid]$siteId, 5 | [guid]$webId, 6 | [guid]$listId, 7 | [mailaddress]$userEmail, 8 | [string]$webUrl, 9 | [string]$webTitle, 10 | [string]$listTitle, 11 | [string]$syncPath 12 | ) 13 | try { 14 | Add-Type -AssemblyName System.Web 15 | #Encode site, web, list, url & email 16 | [string]$siteId = [System.Web.HttpUtility]::UrlEncode($siteId) 17 | [string]$webId = [System.Web.HttpUtility]::UrlEncode($webId) 18 | [string]$listId = [System.Web.HttpUtility]::UrlEncode($listId) 19 | [string]$userEmail = [System.Web.HttpUtility]::UrlEncode($userEmail) 20 | [string]$webUrl = [System.Web.HttpUtility]::UrlEncode($webUrl) 21 | #build the URI 22 | $uri = New-Object System.UriBuilder 23 | $uri.Scheme = "odopen" 24 | $uri.Host = "sync" 25 | $uri.Query = "siteId=$siteId&webId=$webId&listId=$listId&userEmail=$userEmail&webUrl=$webUrl&listTitle=$listTitle&webTitle=$webTitle" 26 | #launch the process from URI 27 | Write-Host $uri.ToString() 28 | start-process -filepath $($uri.ToString()) 29 | } 30 | catch { 31 | $errorMsg = $_.Exception.Message 32 | } 33 | if ($errorMsg) { 34 | Write-Warning "Sync failed." 35 | Write-Warning $errorMsg 36 | } 37 | else { 38 | Write-Host "Sync completed." 39 | while (!(Get-ChildItem -Path $syncPath -ErrorAction SilentlyContinue)) { 40 | Start-Sleep -Seconds 2 41 | } 42 | return $true 43 | } 44 | } 45 | #endregion 46 | #region Main Process 47 | try { 48 | #region Sharepoint Sync 49 | [mailaddress]$userUpn = cmd /c "whoami/upn" 50 | $params = @{ 51 | #replace with data captured from your sharepoint site. 52 | siteId = "{00000000-0000-0000-0000-000000000000}" 53 | webId = "{00000000-0000-0000-0000-000000000000}" 54 | listId = "{00000000-0000-0000-0000-000000000000}" 55 | userEmail = $userUpn 56 | webUrl = "https://example.sharepoint.com" 57 | webTitle = "Title" 58 | listTitle = "FolderName" 59 | } 60 | $params.syncPath = "$(split-path $env:onedrive)\$($userUpn.Host)\$($params.webTitle) - $($Params.listTitle)" 61 | Write-Host "SharePoint params:" 62 | $params | Format-Table 63 | if (!(Test-Path $($params.syncPath))) { 64 | Write-Host "Sharepoint folder not found locally, will now sync.." -ForegroundColor Yellow 65 | $sp = Sync-SharepointLocation @params 66 | if (!($sp)) { 67 | Throw "Sharepoint sync failed." 68 | } 69 | } 70 | else { 71 | Write-Host "Location already syncronized: $($params.syncPath)" -ForegroundColor Yellow 72 | } 73 | #endregion 74 | } 75 | catch { 76 | $errorMsg = $_.Exception.Message 77 | } 78 | finally { 79 | if ($errorMsg) { 80 | Write-Warning $errorMsg 81 | Throw $errorMsg 82 | } 83 | else { 84 | Write-Host "Completed successfully.." 85 | } 86 | } 87 | #endregion -------------------------------------------------------------------------------- /Universal-Print-Printer-Install/Detect.ps1: -------------------------------------------------------------------------------- 1 | #region printer list 2 | $availablePrinters = @( 3 | "Printer A" 4 | "Printer B" 5 | "Printer C" 6 | "Printer D" 7 | ) 8 | $notFound = 0 9 | #endregion 10 | #region check the printers exist 11 | try { 12 | foreach ($p in $availablePrinters) { 13 | if (!(Get-Printer -Name $p -ErrorAction SilentlyContinue)) { 14 | $notFound ++ 15 | } 16 | } 17 | } 18 | catch { 19 | $errorMsg = $_.Exception.Message 20 | } 21 | finally { 22 | if ($errorMsg) { 23 | Write-Warning $errorMsg 24 | exit 1 25 | } 26 | else { 27 | if ($notFound) { 28 | Write-Warning "$notFound printers not found locally.." 29 | exit 1 30 | } 31 | else { 32 | Write-Host "All printers detected.." 33 | exit 0 34 | } 35 | } 36 | } 37 | #endregion -------------------------------------------------------------------------------- /Universal-Print-Printer-Install/Remediate.ps1: -------------------------------------------------------------------------------- 1 | #region printer list 2 | $availablePrinters = @( 3 | [pscustomobject]@{ 4 | SharedID = '2f8aa4d8-8c21-4d37-9506-3da446bcf9ea' 5 | SharedName = 'Printer A' 6 | IsDefault = 'Yes' 7 | } 8 | [pscustomobject]@{ 9 | SharedID = 'c288bc70-8e14-4c5b-9f82-428ecf3ab63a' 10 | SharedName = 'Printer B' 11 | IsDefault = $null 12 | } 13 | [pscustomobject]@{ 14 | SharedID = '478a29db-7bdd-46a7-a75e-e0d61167988c' 15 | SharedName = 'Printer C' 16 | IsDefault = $null 17 | } 18 | [pscustomobject]@{ 19 | SharedID = '896262c5-59ca-4b92-becf-074feb25fccc' 20 | SharedName = 'Printer D' 21 | IsDefault = $null 22 | } 23 | ) 24 | #endregion 25 | try { 26 | $configurationPath = "$env:appdata\UniversalPrintPrinterProvisioning\Configuration" 27 | if (!(Test-Path $configurationPath -ErrorAction SilentlyContinue)) { 28 | New-Item $configurationPath -ItemType Directory -Force | Out-Null 29 | } 30 | $printCfg = ($availablePrinters | ConvertTo-Csv -NoTypeInformation | ForEach-Object { $_ -replace '"', "" } ) -join [System.Environment]::NewLine 31 | $printCfg | Out-File "$configurationPath\printers.csv" -Encoding ascii -NoNewline 32 | Start-Process "${env:ProgramFiles(x86)}\UniversalPrintPrinterProvisioning\Exe\UPPrinterInstaller.exe" -Wait -WindowStyle Hidden 33 | } 34 | catch { 35 | $errorMsg = $_.Exception.Message 36 | } 37 | finally { 38 | if ($errorMsg) { 39 | Write-Warning $errorMsg 40 | exit 1 41 | } 42 | else { 43 | Write-Host "Universal Printer Installer configured and launched. Printers should appear shortly.." 44 | exit 0 45 | } 46 | } -------------------------------------------------------------------------------- /Update-AutoPilotGroupTag/Update-AutoPilotGroupTag.ps1: -------------------------------------------------------------------------------- 1 | function Get-AuthToken { 2 | <# 3 | .SYNOPSIS 4 | This function is used to authenticate with the Graph API REST interface 5 | .DESCRIPTION 6 | The function authenticate with the Graph API Interface with the tenant name 7 | .EXAMPLE 8 | Get-AuthToken 9 | Authenticates you with the Graph API interface 10 | .NOTES 11 | NAME: Get-AuthToken 12 | #> 13 | [cmdletbinding()] 14 | param 15 | ( 16 | [Parameter(Mandatory = $true)] 17 | $user, 18 | 19 | [Parameter(Mandatory = $false)] 20 | [switch]$refreshSession 21 | ) 22 | $userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $user 23 | $tenant = $userUpn.Host 24 | Write-Host "Checking for AzureAD module..." 25 | $aadModule = Get-Module -Name "AzureAD" -ListAvailable 26 | if ($aadModule -eq $null) { 27 | Write-Host "AzureAD PowerShell module not found, looking for AzureADPreview" 28 | $aadModule = Get-Module -Name "AzureADPreview" -ListAvailable 29 | } 30 | if ($aadModule -eq $null) { 31 | write-host 32 | write-host "AzureAD Powershell module not installed..." -f Red 33 | write-host "Install by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt" -f Yellow 34 | write-host "Script can't continue..." -f Red 35 | write-host 36 | exit 37 | } 38 | # Getting path to ActiveDirectory Assemblies 39 | # If the module count is greater than 1 find the latest version 40 | if ($aadModule.count -gt 1) { 41 | $Latest_Version = ($aadModule | Select-Object version | Sort-Object)[-1] 42 | $aadModule = $aadModule | Where-Object { $_.version -eq $Latest_Version.version } 43 | # Checking if there are multiple versions of the same module found 44 | if ($aadModule.count -gt 1) { 45 | $aadModule = $aadModule | Select-Object -Unique 46 | } 47 | $adal = Join-Path $aadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" 48 | $adalforms = Join-Path $aadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" 49 | } 50 | else { 51 | $adal = Join-Path $aadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" 52 | $adalforms = Join-Path $aadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" 53 | } 54 | [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null 55 | [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null 56 | $clientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" 57 | $redirectUri = "urn:ietf:wg:oauth:2.0:oob" 58 | $resourceAppIdURI = "https://graph.microsoft.com" 59 | $authority = "https://login.microsoftonline.com/$Tenant" 60 | try { 61 | $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority 62 | # https://msdn.microsoft.com/en-us/library/azure/microsoft.identitymodel.clients.activedirectory.promptbehavior.aspx 63 | # Change the prompt behaviour to force credentials each time: Auto, Always, Never, RefreshSession 64 | if ($refreshSession) { 65 | $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "RefreshSession" 66 | 67 | } 68 | else { 69 | $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto" 70 | } 71 | $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId") 72 | $authResult = $authContext.AcquireTokenAsync($resourceAppIdURI, $clientId, $redirectUri, $platformParameters, $userId).Result 73 | # If the accesstoken is valid then create the authentication header 74 | if ($authResult.AccessToken) { 75 | # Creating header for Authorization token 76 | $authHeader = @{ 77 | 'Content-Type' = 'application/json' 78 | 'Authorization' = "Bearer " + $authResult.AccessToken 79 | 'ExpiresOn' = $authResult.ExpiresOn 80 | } 81 | return $authHeader 82 | } 83 | else { 84 | Write-Host 85 | Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red 86 | Write-Host 87 | break 88 | } 89 | } 90 | catch { 91 | write-host $_.Exception.Message -f Red 92 | write-host $_.Exception.ItemName -f Red 93 | write-host 94 | break 95 | } 96 | } 97 | function Update-AutoPilotGroupTag { 98 | [cmdletbinding()] 99 | param ( 100 | [parameter(Mandatory = $true)] 101 | [string[]]$deviceSerial, 102 | 103 | [parameter(Mandatory = $false)] 104 | [string]$groupTag, 105 | 106 | [parameter(Mandatory = $false)] 107 | [switch]$sync 108 | ) 109 | try { 110 | if (!($script:authToken)) { 111 | $script:authToken = Get-AuthToken -user $upn 112 | } 113 | $baseUri = 'https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities' 114 | $apDevices = foreach ($sn in $deviceSerial) { 115 | #make sure the device identity exists 116 | $deviceId = (Invoke-RestMethod -Method Get -Uri "$baseUri`?`$filter=contains(serialNumber,'$sn')" -Headers $script:authToken).value 117 | if ($deviceId) { 118 | Write-Host "Found device with id: $deviceSerial" 119 | $deviceId 120 | $body = @{ 121 | groupTag = $(if ($groupTag) { $groupTag } else { '' }) 122 | } 123 | $update = Invoke-WebRequest -Method Post -Uri "$baseUri/$($deviceId.id)/updateDeviceProperties" -Body ($body | ConvertTo-Json -Compress) -Headers $script:authToken -UseBasicParsing 124 | if ($update.StatusCode -eq 200) { 125 | Write-Host "Updated device: $deviceSerial with grouptag: $groupTag" 126 | } 127 | else { 128 | throw "Web requested failed with status code: $update.statusCode" 129 | } 130 | } 131 | } 132 | } 133 | catch { 134 | $errorMsg = $_.Exception.Message 135 | } 136 | finally { 137 | if ($errorMsg) { 138 | Write-Warning $errorMsg 139 | } 140 | else { 141 | if ($sync) { 142 | Write-Host "Autopilot device sync requested.." 143 | Invoke-RestMethod -Method Post -Uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotSettings/sync" -Headers $script:authToken 144 | } 145 | } 146 | } 147 | } 148 | $upn = 'ben@powers-hell.com' 149 | $script:authToken = Get-AuthToken -user $upn 150 | $serials = @( 151 | 'Serial1', 152 | 'Serial2', 153 | 'Serial3' 154 | ) 155 | Update-AutoPilotGroupTag -deviceSerial $serials -groupTag "EXCLUDE" -sync --------------------------------------------------------------------------------