├── Azure ├── ARMTemplates │ ├── azuredeploy.json │ └── deploy.ps1 ├── Automation │ ├── Hybrid │ │ ├── Add-HybridWorker.ps1 │ │ ├── New-OnPremiseHybridWorker.ps1 │ │ ├── Remove-HybridWorker.ps1 │ │ ├── hybrid.ps1 │ │ └── readme.md │ ├── Start-AutomationRunbookPS.ps1 │ ├── Start-AzureCloudVM_script.ps1 │ ├── Start-AzureCloudVM_workflow.ps1 │ ├── Stop-AzureCloudVM_script.ps1 │ ├── Test-StartVirtualMachinesFromWebhook.ps1 │ ├── Test-WebHook-StartVM.ps1 │ └── readme.md ├── AzureAD │ └── reporting-api-signin.ps1 ├── AzurePolicies │ ├── EnumPolicies.ps1 │ └── FirstSteps.ps1 ├── AzureStorageTable │ ├── generate_random_inventorydata.ps1 │ └── intro_storagetable.ps1 ├── Kusto │ └── samples.txt ├── LogAnalytics │ ├── LogAnalyticsQuery.psm1 │ ├── SearchAPI.ps1 │ └── withrestapi.ps1 ├── OMS │ ├── Extract-ManagementPackScripts.ps1 │ ├── Get-ASCDataCollectionEventDetails.ps1 │ ├── Get-OMSOSBaselineDefinitions.ps1 │ ├── Get-OMSSchemaInfo.ps1 │ ├── Send-OMSSample1.ps1 │ ├── Sirona.DataCollectors.txt │ ├── Test-connectivity.ps1 │ ├── UpgradeAnalytics │ │ └── GetWindowsUpgradeAnalyticsdata.ps1 │ ├── eventreferene.ps1 │ ├── eventsrc.txt │ └── omsseclevel.ps1 ├── README.md ├── ResourceManager │ ├── VirtualMachine │ │ ├── CustomScript │ │ │ └── CustomScript1.ps1 │ │ ├── PostVMConfig │ │ │ └── Set-VMPostConfig.ps1 │ │ ├── Template_Win10_1 │ │ │ ├── Deploy_VM.ps1 │ │ │ └── template.json │ │ ├── readme.md │ │ └── vm10 template │ │ │ ├── DEPLOY_TEST.ps1 │ │ │ ├── DEPLOY_VM.ps1 │ │ │ ├── DeploymentHelper.cs │ │ │ ├── deploy.ps1 │ │ │ ├── deploy.sh │ │ │ ├── deployer.rb │ │ │ ├── parameters.json │ │ │ └── template.json │ └── VirtualNetwork │ │ ├── azuredeploy_virtualnetwork.json │ │ ├── azuredeploy_virtualnetwork.parameters.json │ │ ├── new-virtualnetwork.ps1 │ │ └── readme.md └── Utilities │ ├── AzurePSVersion.ps1 │ ├── Cleanup-AzureRmNetworkInterfaces.ps1 │ ├── Cleanup-AzureRmPublicIPAddress.ps1 │ ├── Cleanup-RmNetworkSecurityGroup.ps1 │ ├── Get-AzureBlobInfo.ps1 │ ├── Get-AzureImageSkuInfo.ps1 │ ├── Get-AzureRmVMSizeSpecs.ps1 │ ├── Remove-AzrVirtualMachine.ps1 │ ├── remove-azureblobobject.ps1 │ ├── select-MyAzureRmSubscription.ps1 │ └── wip │ ├── AzureFileShare.ps1 │ ├── AzureRmResourceGroupDeployment.ps1 │ ├── ConfigureWinRM_HTTPS.ps1 │ ├── Scriptsfolder.ps1 │ ├── Untitled1.ps1 │ └── myazure_scripts_new.ps1 ├── BlockChain ├── samples.txt └── stuff.txt ├── CIS ├── Get-CISBenchMarkProfiles.ps1 ├── Install-CISCATToolkit.ps1 ├── Update-CISVulnDefinitions.ps1 └── invoke-ciscat.ps1 ├── ConfigMgr ├── get-cmclientpolicysettings.ps1 └── reame.md ├── ELK └── MyElkPoShSnippets.ps1 ├── GroupPolicy ├── Get-GpoExtensionInfo.ps1 ├── GroupPolicyXtended.psm1 ├── install-GroupPolicyXtended.ps1 └── readme.md ├── LICENSE ├── Office365 ├── LicenseManagement │ └── Get-msoluserlicensestatus.ps1 ├── Monitoring │ └── Get-ServiceHealthDashboard.ps1 ├── README.md ├── RoleManagement │ └── Get-MsolRoleMemberDetails.ps1 ├── UserManagement │ ├── Get-MsolUserInformation.ps1 │ └── New-Office365User.ps1 ├── Utilities │ ├── Disable-MsolUserServicePlan.ps1 │ └── Get-Office365AccountSkuLicensedUsers.ps1 ├── roadmap │ ├── Convert-ExcelSheetToJson.ps1 │ └── get-office365roadmap.ps1 └── wip │ ├── Download-SPOFile.ps1 │ ├── Upload-SPOFile.ps1 │ └── folders.ps1 ├── README.md ├── Security ├── CQureCourseNotes │ └── RecoverFiles.ps1 ├── Get-AuditPolicySettings.ps1 ├── Get-IscMSSecBulletinInfo.ps1 ├── Get-MacVendor.ps1 ├── IPv4PortScan.ps1 ├── MsrcSecurityUpdates_samples.ps1 ├── README.MD ├── SecurityPolicyScript.ps1 ├── Test-OpenPorts.ps1 ├── defender │ ├── Add-DefenderHyperVExclusion.ps1 │ └── Remove-DefenderHyperVExclusion.ps1 ├── get-netconnectiondetails.ps1 ├── install-powersploit.ps1 ├── networking course │ └── notes.md └── pslogs.ps1 ├── Various ├── 1983_HOSTS.TXT ├── Get-IgniteSessions.ps1 ├── Get-oldDODhostswhois.ps1 ├── SYSHST;AR1.txt ├── Update-PoshModule (1).ps1 ├── anothertest.ps1 ├── binarystuff.ps1 ├── convertascidecbin.ps1 ├── findwmi.ps1 ├── geofun.ps1 ├── get-eventidsforprovider.ps1 ├── ignitesessions.txt ├── localposhrepo.ps1 ├── modula.ps1 ├── nat.ps1 ├── oldhostsfile.txt ├── pslogs.ps1 ├── whois_hosts.txt └── wmiexploration.ps1 ├── Windows10 ├── ADKSetup │ └── Setup-ADK.ps1 ├── AppCompat │ └── Start-AppCert.ps1 ├── BIOS_UEFI │ └── get-biostype.ps1 ├── PowerManagement │ └── Get-BatteryChargeStatus.ps1 ├── Security │ ├── processmitigation.ps1 │ ├── tpminfo.ps1 │ └── wdatpcheck.ps1 ├── get-osbuildinfo.ps1 └── readme.md ├── docker ├── ForensicSamples │ ├── Build │ │ ├── build.txt │ │ └── dockerfile │ ├── memory.txt │ └── pescanner.txt ├── One │ ├── app │ │ └── app.txt │ └── dockerfile ├── Two │ ├── dockerfile │ └── howto.txt ├── build.ps1 ├── iis │ ├── Untitled1.ps1 │ ├── dockerfile │ └── iis.ps1 ├── install-dockermodule.ps1 └── portainer.ps1 ├── en-US.pdf ├── forensic └── Get-ShellContent.ps1 ├── kali ├── Get-KaliISO.ps1 └── Kali_Windows_Bash.txt ├── psake ├── default.ps1 └── learn.ps1 └── test └── runme.ps1 /Azure/ARMTemplates/azuredeploy.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", 3 | "contentVersion": "1.0.0.0", 4 | "parameters": { 5 | "storageAccount": { 6 | "type": "string", 7 | "metadata": { 8 | "description": "storage account name - must be unique" 9 | } 10 | }, 11 | "accountType": { 12 | "type": "string", 13 | "defaultValue": "Standard_LRS", 14 | "allowedValues": [ 15 | "Standard_LRS", 16 | "Premium_LRS", 17 | "Standard_RAGRS" 18 | ], 19 | "metadata": { 20 | "description": "SKU Type" 21 | } 22 | } 23 | }, 24 | "variables": {}, 25 | "resources": [ 26 | { 27 | "type": "Microsoft.Storage/storageAccounts", 28 | "name": "[parameters('storageAccount')]", 29 | "apiVersion": "2015-06-15", 30 | "location": "[resourceGroup().location]", 31 | "tags": { 32 | "displayName": "[parameters('storageAccount')]" 33 | }, 34 | "properties": { 35 | "accountType": "[parameters('accountType')]" 36 | 37 | } 38 | } 39 | ], 40 | "outputs": {} 41 | } -------------------------------------------------------------------------------- /Azure/ARMTemplates/deploy.ps1: -------------------------------------------------------------------------------- 1 | 2 | # https://azurecitadel.github.io/workshops/arm/arm-lab1-firstTemplate/ 3 | 4 | 5 | parms="storageAccount=saalever233 accountType=Standard_LRS" 6 | 7 | $rg="lab1" 8 | $template="C:\dev\posh\Azure\ARMTemplates\azuredeploy.json" 9 | $job="job2" 10 | $storageAccount="saalever233" 11 | 12 | -------------------------------------------------------------------------------- /Azure/Automation/Hybrid/Add-HybridWorker.ps1: -------------------------------------------------------------------------------- 1 |  2 | function Add-HybridWorker 3 | { 4 | <# 5 | .Synopsis 6 | Add-HybridWorker 7 | .DESCRIPTION 8 | Add-HybridWorker registers a system as Azure Automation Hybrid Worker 9 | 10 | Important: The SCOM/OMS Agent must be installed on the client prior running 11 | this script. 12 | 13 | .EXAMPLE 14 | Add-HybridWorker -AutomationAccountName Automation01 -ResourceGroupName RG_automation01 -WorkerGroupName WorkerGrp1 15 | #> 16 | [CmdletBinding()] 17 | Param 18 | ( 19 | # Azure Automation Account Name 20 | [Parameter(Mandatory=$true, 21 | ValueFromPipelineByPropertyName=$true, 22 | Position=0)] 23 | [string]$AutomationAccountName, 24 | # Azure Resource Group name 25 | [Parameter(Mandatory=$true, 26 | ValueFromPipelineByPropertyName=$true, 27 | Position=1)] 28 | [string]$ResourceGroupName, 29 | # Hybrid Worker Group Name 30 | [Parameter(Mandatory=$true, 31 | ValueFromPipelineByPropertyName=$true, 32 | Position=2)] 33 | [string]$WorkerGroupName 34 | ) 35 | 36 | Begin 37 | { 38 | $cmdout=@{ 39 | Verbose=If ($PSBoundParameters.Verbose -eq $true) { $true } else { $false }; 40 | Debug=If ($PSBoundParameters.Debug -eq $true) { $true } else { $false } 41 | } 42 | 43 | Write-Verbose "Importing HybridRegistration module" 44 | $agentversion = (Get-ItemProperty -Path "C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\*").Name 45 | Import-Module "C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\$agentversion\HybridRegistration\\HybridRegistration.psd1" @cmdout 46 | } 47 | Process 48 | { 49 | $automationkeyinfo = Get-AzureRmAutomationRegistrationInfo -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName @cmdout 50 | Write-Verbose "Registering Computer to $AutomationAccountName in WorkerGroup $WorkerGroupName" 51 | $cmd = Add-HybridRunbookWorker –Url $automationkeyinfo.Endpoint -Key $automationkeyinfo.PrimaryKey -GroupName $WorkerGroupName @cmdout 52 | } 53 | End 54 | { 55 | } 56 | } 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /Azure/Automation/Hybrid/Remove-HybridWorker.ps1: -------------------------------------------------------------------------------- 1 | function Remove-HybridWorker 2 | { 3 | <# 4 | .Synopsis 5 | Remove-HybridWorker 6 | .DESCRIPTION 7 | Remove-HybridWorker removes a system from an Azure Hybrid Worker Group 8 | 9 | Important: The SCOM/OMS Agent must be installed on the client prior running 10 | this script. 11 | 12 | .EXAMPLE 13 | Remove-HybridWorker -AutomationAccountName Automation01 -ResourceGroupName RG_automation01 14 | #> 15 | [CmdletBinding()] 16 | Param 17 | ( 18 | # Azure Automation Account Name 19 | [Parameter(Mandatory=$true, 20 | ValueFromPipelineByPropertyName=$true, 21 | Position=0)] 22 | [string]$AutomationAccountName, 23 | # Azure Resource Group name 24 | [Parameter(Mandatory=$true, 25 | ValueFromPipelineByPropertyName=$true, 26 | Position=1)] 27 | [string]$ResourceGroupName 28 | ) 29 | 30 | Begin 31 | { 32 | $cmdout=@{ 33 | Verbose=If ($PSBoundParameters.Verbose -eq $true) { $true } else { $false }; 34 | Debug=If ($PSBoundParameters.Debug -eq $true) { $true } else { $false } 35 | } 36 | 37 | 38 | Write-Verbose "Importing HybridRegistration module" 39 | $agentversion = (Get-ItemProperty -Path "C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\*").Name 40 | Import-Module "C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\$agentversion\HybridRegistration\\HybridRegistration.psd1" @cmdout 41 | } 42 | Process 43 | { 44 | $automationkeyinfo = Get-AzureRmAutomationRegistrationInfo -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName @cmdout 45 | Write-Verbose "Removing Computer from $AutomationAccountName" 46 | $cmd = Remove-HybridRunbookWorker -Url $automationkeyinfo.Endpoint -Key $automationkeyinfo.PrimaryKey @cmdout 47 | } 48 | End 49 | { 50 | 51 | } 52 | } 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /Azure/Automation/Hybrid/hybrid.ps1: -------------------------------------------------------------------------------- 1 | # quick and dirty script to make a client that has the OMS AGent already installed 2 | # a hybrid worker. 3 | 4 | $ResourceGroupName = "RG_vAutomation1" 5 | $AutomationAccountName = "vAutomation1" 6 | $HGroupName = "H-WorkerGroup1" 7 | 8 | $agentversion = (Get-ItemProperty -Path "C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\*").Name 9 | cd "C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\$agentversion\HybridRegistration" 10 | Import-Module .\HybridRegistration.psd1 11 | 12 | $automationkeyinfo = Get-AzureRmAutomationRegistrationInfo -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName 13 | 14 | Add-HybridRunbookWorker –Url $automationkeyinfo.Endpoint -Key $automationkeyinfo.PrimaryKey -GroupName $HGroupName -Verbose 15 | 16 | #Remove-HybridRunbookWorker -Url $automationkeyinfo.Endpoint -Key $automationkeyinfo.PrimaryKey -Verbose 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Azure/Automation/Hybrid/readme.md: -------------------------------------------------------------------------------- 1 | # Azure Hybrid Worker Management 2 | 3 | ## Add-HybridWorker.ps1 4 | The Add-HybridWorker cmdlet registers a system as a Hybrid worker, this 5 | script requires that the OMS Agent is already installed on the system. 6 | 7 | ## Remove-HybridWorker.ps1 8 | The Remove-HybridWorker cmdlet removes a system as a Hybrid worker. This 9 | script requires that the OMS Agent is already installed on the system. 10 | 11 | ## New-OnPremiseHybridWorker 12 | Script Source: https://www.powershellgallery.com/packages/New-OnPremiseHybridWorker/1.1/DisplayScript 13 | 14 | This Azure/OMS Automation runbook onboards a local machine as a hybrid worker 15 | 16 | This script does not require that the OMS Agent is already installed. The script 17 | will download and install the agent prior registering it as a hybrid worker. 18 | 19 | Important: Ensure that you provide correct Automation account parameters, otherwise 20 | the script will create a new one. 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Azure/Automation/Start-AutomationRunbookPS.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Sample script to start an Azure Automation Job from PowerShell 3 | 4 | #> 5 | 6 | $runbookName = "Start-AzureCloudVM" 7 | $RbResourceGroupName = "RG_automation01" 8 | $AutomationAcct = "Automation01" 9 | $VMName = "win10vm2" 10 | $ResourceGroupName = "RG_win10vm02" 11 | 12 | 13 | $params = @{ 14 | Name = $VMName; 15 | ResourceGroupName = $ResourceGroupName; 16 | } 17 | 18 | 19 | $job = Start-AzureRmAutomationRunbook –AutomationAccountName $AutomationAcct -Name $runbookName -ResourceGroupName $RbResourceGroupName -Parameters $params 20 | 21 | $doLoop = $true 22 | While ($doLoop) { 23 | $job = Get-AzureRmAutomationJob –AutomationAccountName $AutomationAcct -Id $job.JobId -ResourceGroupName $RbResourceGroupName 24 | $status = $job.Status 25 | $doLoop = (($status -ne "Completed") -and ($status -ne "Failed") -and ($status -ne "Suspended") -and ($status -ne "Stopped")) 26 | } 27 | 28 | Get-AzureRmAutomationJobOutput –AutomationAccountName $AutomationAcct -Id $job.JobId -ResourceGroupName $RbResourceGroupName –Stream Output 29 | 30 | -------------------------------------------------------------------------------- /Azure/Automation/Start-AzureCloudVM_script.ps1: -------------------------------------------------------------------------------- 1 |  2 | <# 3 | .Synopsis 4 | Start-AzureCloudVM 5 | .DESCRIPTION 6 | Start-AzureClouodVM starts an Azure VM 7 | .EXAMPLE 8 | Start-AzureCloudVM -Name win10vm2 -ResourceGroupName RG_win10vm02 9 | #> 10 | Param 11 | ( 12 | # Name of the Virtual Machine 13 | [Parameter(Mandatory=$true, 14 | ValueFromPipelineByPropertyName=$true, 15 | Position=0)] 16 | $Name, 17 | 18 | # Azure ResourceGroup Name 19 | [Parameter(Mandatory=$true, 20 | ValueFromPipelineByPropertyName=$true, 21 | Position=1)] 22 | $ResourceGroupName 23 | ) 24 | 25 | $connectionName = "AzureRunAsConnection" 26 | try 27 | { 28 | # Get the connection "AzureRunAsConnection " 29 | $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName 30 | 31 | "Logging in to Azure..." 32 | Add-AzureRmAccount ` 33 | -ServicePrincipal ` 34 | -TenantId $servicePrincipalConnection.TenantId ` 35 | -ApplicationId $servicePrincipalConnection.ApplicationId ` 36 | -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 37 | } 38 | catch { 39 | if (!$servicePrincipalConnection) 40 | { 41 | $ErrorMessage = "Connection $connectionName not found." 42 | throw $ErrorMessage 43 | } else{ 44 | Write-Error -Message $_.Exception 45 | throw $_.Exception 46 | } 47 | } 48 | 49 | 50 | 51 | Write-verbose "Starting VM $Name in ResourceGroup: $ResourceGroupName" 52 | Start-AzureRmVM -Name $Name -ResourceGroupName $ResourceGroupName 53 | 54 | -------------------------------------------------------------------------------- /Azure/Automation/Start-AzureCloudVM_workflow.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | <# 4 | .Synopsis 5 | Workflow Start-AzureCloudVM 6 | .DESCRIPTION 7 | Workflow Start-AzureClouodVM starts an Azure VM 8 | .EXAMPLE 9 | Start-AzureCloudVM -Name win10vm2 -ResourceGroupName RG_win10vm02 10 | #> 11 | 12 | Workflow Start-AzureCloudVM 13 | { 14 | Param 15 | ( 16 | # Name of the Virtual Machine 17 | [string]$Name, 18 | # Azure ResourceGroup Name 19 | [string]$ResourceGroupName 20 | ) 21 | 22 | 23 | $connectionName = "AzureRunAsConnection" 24 | try 25 | { 26 | # Get the connection "AzureRunAsConnection " 27 | $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName 28 | 29 | "Logging in to Azure..." 30 | Add-AzureRmAccount ` 31 | -ServicePrincipal ` 32 | -TenantId $servicePrincipalConnection.TenantId ` 33 | -ApplicationId $servicePrincipalConnection.ApplicationId ` 34 | -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 35 | } 36 | catch { 37 | if (!$servicePrincipalConnection) 38 | { 39 | $ErrorMessage = "Connection $connectionName not found." 40 | throw $ErrorMessage 41 | } else{ 42 | Write-Error -Message $_.Exception 43 | throw $_.Exception 44 | } 45 | } 46 | 47 | 48 | Write-Verbose "Starting VM $Name in ResourceGroup $ResourceGroupName" 49 | Start-AzureRmVM -Name $Name -ResourceGroupName $ResourceGroupName 50 | 51 | } -------------------------------------------------------------------------------- /Azure/Automation/Stop-AzureCloudVM_script.ps1: -------------------------------------------------------------------------------- 1 |  2 | <# 3 | .Synopsis 4 | Stop-AzureCloudVM 5 | .DESCRIPTION 6 | Stop-AzureClouodVM stops an Azure VM 7 | .EXAMPLE 8 | Stop-AzureCloudVM -Name win10vm2 -ResourceGroupName RG_win10vm02 9 | #> 10 | Param 11 | ( 12 | # Name of the Virtual Machine 13 | [Parameter(Mandatory=$true, 14 | ValueFromPipelineByPropertyName=$true, 15 | Position=0)] 16 | $Name, 17 | 18 | # Azure ResourceGroup Name 19 | [Parameter(Mandatory=$true, 20 | ValueFromPipelineByPropertyName=$true, 21 | Position=1)] 22 | $ResourceGroupName 23 | ) 24 | 25 | $connectionName = "AzureRunAsConnection" 26 | try 27 | { 28 | # Get the connection "AzureRunAsConnection " 29 | $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName 30 | 31 | "Logging in to Azure..." 32 | Add-AzureRmAccount ` 33 | -ServicePrincipal ` 34 | -TenantId $servicePrincipalConnection.TenantId ` 35 | -ApplicationId $servicePrincipalConnection.ApplicationId ` 36 | -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 37 | } 38 | catch { 39 | if (!$servicePrincipalConnection) 40 | { 41 | $ErrorMessage = "Connection $connectionName not found." 42 | throw $ErrorMessage 43 | } else{ 44 | Write-Error -Message $_.Exception 45 | throw $_.Exception 46 | } 47 | } 48 | 49 | 50 | 51 | Write-verbose "Starting VM $Name in ResourceGroup: $ResourceGroupName" 52 | Stop-AzureRmVM -Name $Name -ResourceGroupName $ResourceGroupName -Verbose -Force 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /Azure/Automation/Test-StartVirtualMachinesFromWebhook.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Test-StartVirtualMachinesFromWebhook 4 | .DESCRIPTION 5 | Test-StartVirtualMachinesFromWebhook is called via a webook and stops the 6 | specified VMs 7 | #> 8 | workflow Test-StartVirtualMachinesFromWebhook 9 | { 10 | param ( 11 | [object]$WebhookData 12 | ) 13 | 14 | # If runbook was called from Webhook, WebhookData will not be null. 15 | if ($WebhookData -ne $null) { 16 | 17 | # Collect properties of WebhookData 18 | $WebhookName = $WebhookData.WebhookName 19 | $WebhookHeaders = $WebhookData.RequestHeader 20 | $WebhookBody = $WebhookData.RequestBody 21 | 22 | # Collect individual headers. VMList converted from JSON. 23 | $From = $WebhookHeaders.From 24 | $VMList = ConvertFrom-Json -InputObject $WebhookBody 25 | Write-Output "Runbook started from webhook $WebhookName by $From." 26 | 27 | # Authenticate to Azure resources 28 | $connectionName = "AzureRunAsConnection" 29 | try 30 | { 31 | # Get the connection "AzureRunAsConnection " 32 | $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName 33 | 34 | "Logging in to Azure..." 35 | Add-AzureRmAccount ` 36 | -ServicePrincipal ` 37 | -TenantId $servicePrincipalConnection.TenantId ` 38 | -ApplicationId $servicePrincipalConnection.ApplicationId ` 39 | -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 40 | } 41 | catch { 42 | if (!$servicePrincipalConnection) 43 | { 44 | $ErrorMessage = "Connection $connectionName not found." 45 | throw $ErrorMessage 46 | } else{ 47 | Write-Error -Message $_.Exception 48 | throw $_.Exception 49 | } 50 | } 51 | 52 | # Start each virtual machine 53 | foreach ($VM in $VMList) 54 | { 55 | $VMName = $VM.Name 56 | Write-Output "Starting $VMName" 57 | Start-AzureRMVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName 58 | } 59 | } 60 | else { 61 | Write-Error "Runbook mean to be started only from webhook." 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Azure/Automation/Test-WebHook-StartVM.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Test-WebHook-StartVM 4 | .DESCRIPTION 5 | Test-WebHook-StartVM triggers the webhook for Test-StartVirtualMachinesFromWebhook 6 | #> 7 | 8 | 9 | # Web hook, start Azue VM 10 | $uri = "https://s2events.azure-automation.net/webhooks?token=FjN6C4OOD2d7T%2fAKhUfnZajjEzBM8YFUNshf1wEO%2bt4%3d" 11 | $headers = @{"From"="alex@contoso.com";"Date"="02/9/2017 16:47:00"} 12 | 13 | $vms = @( 14 | @{ Name="win10vm2";ResourceGroupName="RG_win10vm02"} 15 | ) 16 | $body = ConvertTo-Json -InputObject $vms 17 | 18 | $response = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body 19 | $job = $response.JobIds 20 | 21 | -------------------------------------------------------------------------------- /Azure/Automation/readme.md: -------------------------------------------------------------------------------- 1 | # Azure Automation 2 | Work Notes and sample scripts I created while learning Azure Automation 3 | 4 | 5 | ## Start-AzureCloudVM_workflow.ps1 6 | Sample of a workflow runbook to start an Azure VM 7 | 8 | ## Start-AzureCloudVM_script.ps1 9 | Sample of powershell script runbook to start an Azure VM 10 | 11 | ## Start-AutomationRunbookPS.ps1 12 | Sample of starting an Automation Runbook from PowerShell 13 | 14 | ## Test-WebHook-StartVM 15 | Sample for trigger a webhook, this script triggers the webhook for 16 | the Test-StartVirtualMachinesFromWebhook workflow. 17 | 18 | ## Test-StartVirtualMachinesFromWebhook 19 | Sample workflow script that is triggered via a webhook (See Test-WebHook-StartVM) 20 | The script itself starts the VMs that are specified as parameters to the webhook. 21 | 22 | 23 | 24 | 25 | # Documentation references 26 | https://docs.microsoft.com/en-us/azure/automation/automation-solution-vm-management 27 | https://docs.microsoft.com/en-us/azure/automation/automation-first-runbook-textual 28 | https://docs.microsoft.com/en-us/azure/automation/automation-runbook-output-and-messages 29 | https://docs.microsoft.com/en-us/azure/automation/automation-starting-a-runbook#starting-a-runbook-with-windows-powershell 30 | 31 | -------------------------------------------------------------------------------- /Azure/AzureAD/reporting-api-signin.ps1: -------------------------------------------------------------------------------- 1 |  2 | # https://docs.microsoft.com/en-us/azure/active-directory/active-directory-reporting-api-sign-in-activity-samples 3 | 4 | # This script will require the Web Application and permissions setup in Azure Active Directory 5 | $ClientID = "5c5b39cd-87ab-4a81-84e7-8c0f5799d585" # Should be a ~35 character string insert your info here 6 | $ClientSecret = "<>" # Should be a ~44 character string insert your info here 7 | $loginURL = "https://login.microsoftonline.com/" 8 | $tenantdomain = "verboononline.onmicrosoft.com" 9 | $daterange # For example, contoso.onmicrosoft.com 10 | 11 | $7daysago = "{0:s}" -f (get-date).AddDays(-7) + "Z" 12 | # or, AddMinutes(-5) 13 | 14 | Write-Output $7daysago 15 | 16 | # Get an Oauth 2 access token based on client id, secret and tenant domain 17 | $body = @{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret} 18 | 19 | $oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body $body 20 | 21 | if ($oauth.access_token -ne $null) { 22 | $headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"} 23 | 24 | $url = "https://graph.windows.net/$tenantdomain/activities/signinEvents?api-version=beta&`$filter=signinDateTime ge $7daysago" 25 | 26 | $i=0 27 | 28 | Do{ 29 | Write-Output "Fetching data using Uri: $url" 30 | $myReport = (Invoke-WebRequest -UseBasicParsing -Headers $headerParams -Uri $url) 31 | Write-Output "Save the output to a file SigninActivities$i.json" 32 | Write-Output "---------------------------------------------" 33 | $myReport.Content | Out-File -FilePath SigninActivities$i.json -Force 34 | $url = ($myReport.Content | ConvertFrom-Json).'@odata.nextLink' 35 | $i = $i+1 36 | } while($url -ne $null) 37 | 38 | } else { 39 | 40 | Write-Host "ERROR: No Access Token" 41 | } -------------------------------------------------------------------------------- /Azure/AzurePolicies/EnumPolicies.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-xAzureRmPolicySetDefinitionDetails 3 | { 4 | <# 5 | 6 | #> 7 | 8 | [CmdletBinding()] 9 | 10 | Param() 11 | 12 | Begin{ 13 | 14 | Try{ 15 | $AzPolSetDef = Get-AzureRmPolicySetDefinition 16 | } 17 | Catch 18 | { 19 | Write-error "Unable to retrieve Azure Policy Definitions" 20 | Throw 21 | } 22 | 23 | } 24 | 25 | Process{ 26 | ForEach ($PolSet in $AzPolSetDef) 27 | { 28 | Write-Verbose "Processing $($polset.displayName)" 29 | 30 | # Get all all PolicyDefintiions included in the PolicySet 31 | $includedpoldef = ($PolSet.Properties.policyDefinitions).policyDefinitionId 32 | 33 | $Result = @() 34 | ForEach ($Azpoldef in $includedpoldef) 35 | { 36 | $def = Get-AzureRmPolicyDefinition -Id $Azpoldef 37 | 38 | $object = [ordered] @{ 39 | PolicySetDefName = $PolSet.Name 40 | PolicySetDefID = $Polset.PolicySetDefinitionId 41 | PolicySetDefDisplayName = $Polset.Properties.displayName 42 | PolicySetDefResourceID = $polset.ResourceId 43 | PolicyDefID = $def.PolicyDefinitionId 44 | PolicyDefResourceID = $def.ResourceId 45 | PolicyName = $def.Name 46 | PolicyID = $def.PolicyDefinitionId 47 | PolicyDescription = $def.Properties.description 48 | PolicyDisplayName = $def.Properties.displayName 49 | PolicyCategory = $def.Properties.metadata.category 50 | PolicyMode = $def.Properties.mode 51 | PolicyParam = $def.Properties.parameters 52 | PolicyRuleIf = $def.Properties.policyRule.if 53 | PolicyRuleThen = $def.Properties.policyRule.then 54 | PolicyType = $def.Properties.policyType 55 | } 56 | $Result += (New-Object -TypeName PSObject -Property $object) 57 | } 58 | } 59 | } 60 | 61 | End{ 62 | $Result 63 | } 64 | } -------------------------------------------------------------------------------- /Azure/AzurePolicies/FirstSteps.ps1: -------------------------------------------------------------------------------- 1 | # Azure Policy - First Steps 2 | 3 | # https://docs.microsoft.com/en-us/azure/azure-policy/azure-policy-introduction 4 | 5 | # available PowerShell cmdlets 6 | get-command -Module AzureRM.Resources -Name *Policy* 7 | 8 | <# 9 | Get-AzureRmPolicyAssignment 10 | Get-AzureRmPolicyDefinition 11 | Get-AzureRmPolicySetDefinition 12 | New-AzureRmPolicyAssignment 13 | New-AzureRmPolicyDefinition 14 | New-AzureRmPolicySetDefinition 15 | Remove-AzureRmPolicyAssignment 16 | Remove-AzureRmPolicyDefinition 17 | Remove-AzureRmPolicySetDefinition 18 | Set-AzureRmPolicyAssignment 19 | Set-AzureRmPolicyDefinition 20 | Set-AzureRmPolicySetDefinition 21 | #> 22 | 23 | # Examples Repo 24 | #https://github.com/Azure/azure-policy 25 | 26 | 27 | -------------------------------------------------------------------------------- /Azure/AzureStorageTable/generate_random_inventorydata.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | $locations = @("Amsterdam","Paris","Stockholm","London","New York","Seatle","Singapure","Hong Kong","The Hague","Barcelona","Madrid","Stockholm","Rome") 4 | 5 | $data = @() 6 | $count = 0 7 | While ($count -le 100) 8 | { 9 | $obj = @{ 10 | RowKey = ([guid]::NewGuid().tostring()) 11 | PartitionKey = "Inventory" 12 | ComputerName = "Computer" + $count.ToString("000000") 13 | Location = ($locations)[(Get-Random -Minimum 0 -Maximum $locations.Count )] 14 | dtDate = [datetime]::UtcNow 15 | } 16 | $data += (New-Object -TypeName PSCustomObject -Property $obj) 17 | $count++ 18 | } -------------------------------------------------------------------------------- /Azure/AzureStorageTable/intro_storagetable.ps1: -------------------------------------------------------------------------------- 1 |  2 | # https://docs.microsoft.com/en-us/rest/api/storageservices/querying-tables-and-entities 3 | # https://blog.tyang.org/2016/11/30/powershell-module-for-managing-azure-table-storage-entities/ 4 | # https://www.powershellgallery.com/packages/AzureTableEntity/1.0.0.0 5 | # https://github.com/tyconsulting/AzureTableEntity-PowerShell-Module 6 | # https://docs.microsoft.com/en-us/rest/api/storageservices/designing-a-scalable-partitioning-strategy-for-azure-table-storage 7 | 8 | 9 | $subscriptionName = "MSDN Platforms" 10 | 11 | # Create ResourceGroup 12 | $Location = "Westeurope" 13 | $ComputerInventory_ResourceGroup = "rg_CompComputerInventory" 14 | New-AzureRmResourceGroup -Name $ComputerInventory_ResourceGroup -Location $Location 15 | 16 | # Create StorageAccount 17 | $SkuName = "Standard_LRS" 18 | $ComputerInventory_StorageAccountName = "sacomputerinventory" 19 | New-AzureRmStorageAccount -ResourceGroupName $ComputerInventory_ResourceGroup -Name $ComputerInventory_StorageAccountName -SkuName "$SkuName" -Location $Location 20 | 21 | # Retrieve the first StorageAccountAccessKey 22 | $StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $ComputerInventory_ResourceGroup -Name $ComputerInventory_StorageAccountName 23 | $StorageAccountAccessKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $ComputerInventory_ResourceGroup -Name $ComputerInventory_StorageAccountName).Value[0] 24 | 25 | #Create Table 26 | $TableName = "ComputerInventory" 27 | $context = New-AzureStorageContext -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountKey $StorageAccountAccessKey 28 | New-AzureStorageTable -Name $TableName -Context $context 29 | 30 | 31 | # Add one entry 32 | $data = @{ 33 | RowKey = ([guid]::NewGuid().tostring()) 34 | PartitionKey = "Inventory" 35 | ComputerName = "Computer000001" 36 | Location = "Amsterdam" 37 | dtDate = [datetime]::UtcNow 38 | } 39 | 40 | New-AzureTableEntity -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountAccessKey $StorageAccountAccessKey -TableName $TableName -Verbose -Entities $data 41 | 42 | # Generate some demo data for PC inventory 43 | 44 | $locations = @("Amsterdam","Paris","Stockholm","London","New York","Seatle","Singapure","Hong Kong","The Hague","Barcelona","Madrid","Stockholm","Rome") 45 | $data = @() 46 | $count = 2 47 | While ($count -le 100) 48 | { 49 | $obj = @{ 50 | RowKey = ([guid]::NewGuid().tostring()) 51 | PartitionKey = "Inventory" 52 | ComputerName = "Computer" + $count.ToString("000000") 53 | Location = ($locations)[(Get-Random -Minimum 0 -Maximum $locations.Count )] 54 | dtDate = [datetime]::UtcNow 55 | } 56 | $data += (New-Object -TypeName PSCustomObject -Property $obj) 57 | $count++ 58 | } 59 | 60 | 61 | # Add rows to Azure Storage Table 62 | New-AzureTableEntity -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountAccessKey $StorageAccountAccessKey -TableName $TableName -Verbose -Entities $data 63 | 64 | # Retrieve Table Data 65 | $querystring = "(PartitionKey eq 'Inventory')" 66 | $result = Get-AzureTableEntity -TableName $tableName -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountAccessKey $StorageAccountAccessKey -QueryString $querystring -ConvertDateTimeFields $true -GetAll $true -Verbose 67 | $result.Count 68 | $result | Group-Object Location 69 | 70 | 71 | # only computer1 72 | $querystring = "(ComputerName eq 'Computer000001')" 73 | $result = Get-AzureTableEntity -TableName $tableName -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountAccessKey $StorageAccountAccessKey -QueryString $querystring -ConvertDateTimeFields $true -GetAll $true -Verbose 74 | $result 75 | 76 | $NewLoczation = "Rotterdam" 77 | 78 | $data = @{ 79 | PartitionKey = $result.PartitionKey 80 | RowKey = $result.RowKey 81 | Location = $NewLoczation 82 | ComputerName = $result.ComputerName 83 | dtDate = $result.dtDate 84 | } 85 | 86 | Update-AzureTableEntity -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountAccessKey $StorageAccountAccessKey -TableName $TableName -Entities $data 87 | $querystring = "(ComputerName eq 'Computer000001')" 88 | $result = Get-AzureTableEntity -TableName $tableName -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountAccessKey $StorageAccountAccessKey -QueryString $querystring -ConvertDateTimeFields $true -GetAll $true -Verbose 89 | $result 90 | 91 | 92 | 93 | $Remove = @{ 94 | PartitionKey = $result.PartitionKey 95 | RowKey = $result.RowKey 96 | Computername = $result.ComputerName 97 | } 98 | 99 | Remove-AzureTableEntity -StorageAccountName $ComputerInventory_StorageAccountName -StorageAccountAccessKey $StorageAccountAccessKey -TableName $TableName -Entities $Remove 100 | 101 | -------------------------------------------------------------------------------- /Azure/Kusto/samples.txt: -------------------------------------------------------------------------------- 1 | 2 | browserTimings 3 | | project client_Browser, client_OS , client_City 4 | 5 | browserTimings 6 | | where timestamp > ago(7d) 7 | | summarize count() by client_City 8 | | render barchart 9 | 10 | https://portal.loganalytics.io/demo#/discover/home 11 | https://analytics.applicationinsights.io/demo#/discover/query/results/table 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Azure/LogAnalytics/SearchAPI.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | Azure Log Analytics queries 4 | # https://dev.loganalytics.io/ 5 | # https://docs.loganalytics.io/index 6 | # https://dev.loganalytics.io/documentation/Tools/PowerShell-Cmdlets 7 | # https://blogs.technet.microsoft.com/cbernier/2018/02/15/windows-update-compliance-querying-azure-log-analytics-data-using-powershell/ 8 | 9 | #> 10 | 11 | $subscrID = "53fac23e-0234-4aa0-9097-0bd02896b7cf" 12 | $WorkspaceName = "automation01oms" 13 | $resourcegroupname = "rg_automation01" 14 | $WorkspaceID = "197c29e4-5914-40e7-bea0-7a718679f5f7" 15 | 16 | Import-Module -FullyQualifiedName "c:\dev\posh\Azure\LogAnalytics\LogAnalyticsQuery.psm1" -DisableNameChecking 17 | <# 18 | $query = " 19 | SecurityBaseline 20 | | where BaselineType in ('WindowsOS', 'Linux') and AnalyzeResult=='Failed' 21 | | summarize Count=count() by BaselineRuleId, Description, RuleSeverity, AssessmentId, Computer 22 | | order by Count desc 23 | " 24 | #> 25 | $query = "SecurityEvent 26 | | where TimeGenerated > ago(1d) 27 | | summarize count() by tostring(EventID), AccountType, bin(TimeGenerated, 1h)" 28 | 29 | 30 | $Result = Invoke-LogAnalyticsQuery -WorkspaceName $WorkspaceName -SubscriptionId $subscrID -ResourceGroup $resourcegroupname -Query $query -IncludeTabularView -IncludeStatistics 31 | 32 | $Result.Results 33 | 34 | 35 | -------------------------------------------------------------------------------- /Azure/LogAnalytics/withrestapi.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | $headers = @{ 4 | "Authorization" = "Bearer $accesstoken"; 5 | } 6 | 7 | $uri = "https://management.azure.com/subscriptions/$subscrID/resourceGroups/$resourcegroupname/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/api/query?api-version=2017-01-01-preview" 8 | 9 | 10 | $body = @{ 11 | "query" = $query; 12 | "timespan" = $Timespan 13 | } | ConvertTo-Json 14 | 15 | $response = Invoke-WebRequest -Uri $uri -Headers $headers -Method Post -ContentType "application/json" -Body $body 16 | 17 | $data = $response.Content | ConvertFrom-Json 18 | 19 | -------------------------------------------------------------------------------- /Azure/OMS/Extract-ManagementPackScripts.ps1: -------------------------------------------------------------------------------- 1 | Function Extract-ManagementPackScrpts 2 | { 3 | <# 4 | .SYNOPSIS 5 | Extract-ManagementPackScrpts 6 | .DESCRIPTION 7 | The Extract-ManagementPackScrpts cmdlet parses through the 8 | ManagementPack xml definition files and extracts Code that 9 | is embedded within the 'ScriptBody" Node. 10 | .PARAMETER ScriptOutFldr 11 | Location where found script content is saved to. 12 | 13 | .EXAMPLE 14 | Extract-ManagementPackScrpts 15 | 16 | The above command parses through all Management Pack 17 | XML definition files located in the folder 18 | C:\Program Files\Microsoft Monitoring Agent\Agent\Health Service State\Management Packs 19 | and saves the found script content to C:\TEMP\ScrOut 20 | 21 | .NOTES 22 | The extracted scripts will not run because there's still 23 | some HTML code within the scripts, but you can popen the 24 | scripts in VSCODE to study the content. 25 | #> 26 | 27 | 28 | [CmdletBinding()] 29 | Param( 30 | # Output folder to save found script content 31 | [string]$ScriptOutFldr = "C:\TEMP\ScrOut" 32 | ) 33 | 34 | # Location of OMS Management Packs 35 | $ManagementPackFldr = "C:\Program Files\Microsoft Monitoring Agent\Agent\Health Service State\Management Packs" 36 | 37 | 38 | 39 | If ((Test-Path "$ManagementPackFldr") -eq $false) 40 | { 41 | Write-Warning "Management Pack Folder: $ManagementPackFldr not found" 42 | Throw 43 | } 44 | 45 | 46 | If ((Test-Path "$ScriptOutFldr") -eq $false ) 47 | { 48 | New-Item "$ScriptOutFldr" -ItemType Directory 49 | } 50 | 51 | 52 | $files = Get-ChildItem "$ManagementPackFldr\*.xml" -Recurse 53 | $Result = @() 54 | 55 | foreach ( $file in $files ) 56 | { 57 | Write-verbose "Processing $($file.Name)" 58 | [System.Xml.XmlDocument]$doc = new-object System.Xml.XmlDocument; 59 | $doc.set_PreserveWhiteSpace( $true ); 60 | $doc.Load( $file ); 61 | $root = $doc.get_DocumentElement(); 62 | $xml = $root.get_outerXml() 63 | $xml = '' + $xml 64 | $newFile = "$env:temp\$($file.Name)" + ".new" 65 | 66 | Set-Content -Encoding UTF8 $newFile $xml 67 | 68 | # find ScriptBody Nodes 69 | $scripts = Select-Xml -Path $newFile -XPath "//ScriptBody" 70 | $scount=1 71 | ForEach ($script in $scripts) 72 | { 73 | # ScriptBody 74 | $ScriptBody = $script.Node.InnerXml 75 | If ($ScriptBody -ne "`$Config/ScriptBody$") 76 | { 77 | $object = @{ 78 | ManagementPack = $File.Name 79 | ScriptBody = $ScriptBody 80 | } 81 | $Result += (New-Object -TypeName PSObject -Property $object) 82 | 83 | $object.ScriptBody | Out-File -FilePath ("$ScriptOutFldr\$($file.name)_$scount"+".ps1") -Encoding unicode -NoNewline 84 | $scount++ 85 | } 86 | } 87 | Remove-Item -Path $newFile -Force 88 | } 89 | 90 | Write-output "Scripts found in the following Management Packs" 91 | write-output "" 92 | 93 | $Result | Select-Object ManagementPack 94 | 95 | write-output "" 96 | Write-output "Script sources saved to $ScriptOutFldr" 97 | 98 | } 99 | -------------------------------------------------------------------------------- /Azure/OMS/Get-ASCDataCollectionEventDetails.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-ASCDataCollectionEventDetails{ 3 | 4 | <# 5 | .SYNOPSIS 6 | Get-ASCDataCollectionEventDetails 7 | 8 | .DESCRIPTION 9 | Get-ASCDataCollectionEventDetails retrieves Event information based 10 | on a provided set of EventIDs 11 | 12 | .PARAMETER Scope 13 | Minimum or Common 14 | 15 | .EXAMPLE 16 | Get-ASCDataCollectionEventDetails -Scope Minimal -Verbose 17 | 18 | Lists all Event IDs and Event information for the Minimal scope 19 | 20 | .NOTES 21 | https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/appendix-l--events-to-monitor 22 | https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/advanced-security-audit-policy-settings 23 | https://docs.microsoft.com/en-us/azure/security-center/security-center-enable-data-collection#data-collection-tier 24 | #> 25 | 26 | 27 | [CmdLetBinding()] 28 | Param( 29 | [Parameter(Mandatory=$true,Position=1)] 30 | [ValidateSet('Minimal',"Common")] 31 | [string]$Scope 32 | ) 33 | 34 | Begin{ 35 | 36 | # Events Inculded in "minimal" data collection 37 | $Minimal = ("1102","4624","4625","4657","4663","4688","4700","4702","4719","4720","4722","4723","4724","4727","4728","4732","4735","4737","4739","4740","4754","4755","4756","4767","4799","4825","4946","4948","4956","5024","5033","8001","8002","8003","8004","8005","8006","8007","8222") 38 | 39 | # Events Inculded in "Common" data collection 40 | $Common = ("1","299","300","324","340","403","404","410","411","412","413","431","500","501","1100","1102","1107","1108","4608","4610","4611","4614","461","4622", 41 | "4624","4625","4634","4647","4648","4649","4657","4661","4662","4663","4665","4666","4667","4688","4670","4672","4673","4674","4675","4689","4697", 42 | "4700","4702","4704","4705","4716","4717","4718","4719","4720","4722","4723","4724","4725","4726","4727","4728","4729","4733","4732","4735","4737", 43 | "4738","4739","4740","4742","4744","4745","4746","4750","4751","4752","4754","4755","4756","4757","4760","4761","4762","4764","4767","4768","4771", 44 | "4774","4778","4779","4781","4793","4797","4798","4799","4800","4801","4802","4803","4825","4826","4870","4886","4887","4888","4893","4898","4902", 45 | "4904","4905","4907","4931","4932","4933","4946","4948","4956","4985","5024","5033","5059","5136","5137","5140","5145","5632","6144","6145","6272", 46 | "6273","6278","6416","6423","6424","8001","8002","8003","8004","8005","8006","8007","8222","26401","30004") 47 | 48 | 49 | If ($Scope -eq "Minimal") 50 | { 51 | $EventScope = $Minimal 52 | } 53 | ElseIf($Scope -eq "Common") 54 | { 55 | $EventScope = $Common 56 | } 57 | } 58 | 59 | Process{ 60 | Write-Verbose "Processing Scope: $Scope" 61 | 62 | $EventIDReference = $null 63 | $EventLogProviders = "Microsoft-Windows-Security-Auditing","Microsoft-Windows-AppLocker","Microsoft-Windows-Security-Kerberos","Microsoft-Windows-eventlog","Microsoft-Windows-TaskScheduler","Microsoft-Windows-WinRM","Microsoft-Windows-WinLogon" 64 | ForEach ($entry in $EventLogProviders) 65 | { 66 | $EventIDList = (Get-Winevent -ListProvider $entry).events 67 | $EventIDList | Add-Member -MemberType NoteProperty -Name Provider -Value "$entry" 68 | $EventIDReference = $EventIDReference + $EventIDList 69 | } 70 | 71 | 72 | $Result = @() 73 | 74 | ForEach ($ScopeID in $EventScope) 75 | { 76 | Write-verbose "Processing EventID $ScopeID" 77 | $detail = $EventIDReference | Where-Object {$_.id -eq $ScopeID} 78 | 79 | If ([string]::IsNullOrEmpty($detail)) 80 | { 81 | $Found = $false 82 | $Detail = New-Object -TypeName PSObject 83 | $Detail | Add-Member -Name "ID" -Value $ScopeID -MemberType NoteProperty 84 | } 85 | Else 86 | { 87 | $Found = $true 88 | } 89 | 90 | ForEach ($detailentry in $detail) 91 | { 92 | $object = [ordered] @{ 93 | Id = $ScopeID 94 | Description = $detailentry.description 95 | ShortDesription = If([string]::IsNullOrEmpty($detailentry.Description)) {$null} Else {$detailentry.Description.split("`r`n")[0]} 96 | Level = $detailentry.Level.DisplayName 97 | LogLink = $detailentry.LogLink.DisplayName 98 | Provider = $detailentry.provider 99 | # indicates whether the EventID could be looked up 100 | Found = $found 101 | } 102 | $Result += (New-Object -TypeName PSObject -Property $object) 103 | } 104 | } 105 | } 106 | 107 | End{ 108 | $Result 109 | } 110 | } 111 | 112 | 113 | -------------------------------------------------------------------------------- /Azure/OMS/Get-OMSOSBaselineDefinitions.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-OMSOSBaselineDefinitions { 3 | <# 4 | .SYNOPSIS 5 | Get-OMSOSBaselineDefinitions 6 | .DESCRIPTION 7 | Get-OMSOSBaselineDefinitions lists Configuration data from the selected 8 | OMS Security configuration baseline definition file. 9 | 10 | These files are stored wihtin subfolders under: 11 | "C:\Program Files\Microsoft Monitoring Agent\Agent\Health Service State\Resources" 12 | 13 | .PARAMETER Baseline 14 | The filename of the OMS Security Configuration Baseline 15 | 16 | .EXAMPLE 17 | Get-OMSOSBaselineDefinitions -Baseline 'C:\Program Files\Microsoft Monitoring Agent\Agent\Health Service State\Resources\689\BaselineWindowsServer2016.xml' 18 | 19 | The above command lists all the Security Configuration Baseline definitions for 20 | the Windows Server 2016 operating system. 21 | 22 | .NOTES 23 | v1.0, 19.02.2018, alex verboon 24 | #> 25 | [CmdletBinding()] 26 | Param( 27 | ) 28 | 29 | DynamicParam { 30 | 31 | # Set the dynamic parameters' name 32 | $ParameterName = 'Baseline' 33 | # Create the dictionary 34 | $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary 35 | # Create the collection of attributes 36 | $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] 37 | # Create and set the parameters' attributes 38 | $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute 39 | $ParameterAttribute.Mandatory = $true 40 | #$ParameterAttribute.Position = 3 41 | # Add the attributes to the attributes collection 42 | $AttributeCollection.Add($ParameterAttribute) 43 | # Generate and set the ValidateSet 44 | $BaseLinePath = "C:\Program Files\Microsoft Monitoring Agent\Agent\Health Service State\Resources" 45 | $arrSet = Get-ChildItem -Path "$BaseLinePath\*BaseLine*.xml" -Recurse -Depth 2 46 | #$arrSet = Get-ChildItem -Path "$CISCATPath\CIS-CAT-FULL\Benchmarks" -Filter "*.xml" 47 | $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) 48 | 49 | # Add the ValidateSet to the attributes collection 50 | $AttributeCollection.Add($ValidateSetAttribute) 51 | 52 | # Create and return the dynamic parameter 53 | $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) 54 | $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) 55 | return $RuntimeParameterDictionary 56 | } 57 | 58 | Begin{ 59 | Write-verbose "Selected Baseline: $($PSBoundParameters["Baseline"])" 60 | } 61 | 62 | Process{ 63 | $Result = @() 64 | $Rules = @("BaselineRegistryRule","BaselineAuditPolicyRule","BaselineSecurityPolicyRule") 65 | ForEach ($RuleType in $Rules) 66 | { 67 | write-verbose "Processing Rule: $RuleType" 68 | $blfile = "$($PSBoundParameters["Baseline"])" 69 | 70 | 71 | write-host "$($blfile.name)" 72 | If (-not ($blfile.name -eq "WebBaseLineRules.xml")) 73 | { 74 | $Baselines = Select-xml -Path $blfile -XPath "//$RuleType" 75 | } 76 | Elseif ($blfile.Name -eq "WebBaseLineRules.xml") 77 | { 78 | $Baselines = Select-xml -Path $blfile -XPath "//WebBaselineRule" 79 | $RuleType = "WebBaselineRule" 80 | } 81 | 82 | ForEach ($BRule in $baselines.node) 83 | { 84 | $object = [ordered] @{ 85 | BaselineFile = $blfile 86 | RuleType = $RuleType 87 | BaselineId = $BRule.BaselineId 88 | Id = $BRule.Id 89 | OriginalId = $BRule.OriginalId 90 | CceId = $BRule.CceId 91 | Name = $BRule.Name 92 | Type = $BRule.Type 93 | ExpectedValue = $BRule.ExpectedValue 94 | Severity = $BRule.Severity 95 | AnalyzeOperation = $BRule.AnalyzeOperation 96 | Enabled = $BRule.Enabled 97 | AuditPolicyId = $BRule.AuditPolicyId 98 | } 99 | $Result += (New-Object -TypeName PSOBJECT -Property $object) 100 | } 101 | } 102 | } 103 | 104 | End{ 105 | $Result 106 | } 107 | } 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /Azure/OMS/Get-OMSSchemaInfo.ps1: -------------------------------------------------------------------------------- 1 |  2 | function Get-OMSSchemaInfo 3 | { 4 | <# 5 | .Synopsis 6 | Get-OMSSchemaInfo 7 | .DESCRIPTION 8 | Get-OMSSchemaInfo 9 | .EXAMPLE 10 | Get-OMSSchemaInfo -ResourceGroupName mms-weu -WorkSpaceName AlexVerboonOMS 11 | 12 | lists all schema information 13 | 14 | .EXAMPLE 15 | Get-OMSSchemaInfo -ResourceGroupName mms-weu -WorkSpaceName AlexVerboonOMS | Where-Object {$_.OwnerType -like "MyComputers*"} 16 | 17 | lists all schmea information where owner type string starts with "MyComputers" 18 | 19 | 20 | #> 21 | [CmdletBinding()] 22 | Param 23 | ( 24 | # The name of the Azure ResourceGroup 25 | [Parameter(Mandatory=$true, 26 | ValueFromPipelineByPropertyName=$true, 27 | Position=0)] 28 | [string]$ResourceGroupName, 29 | # The name of the OMS Workspace 30 | [Parameter(Mandatory=$true, 31 | ValueFromPipelineByPropertyName=$true, 32 | Position=0)] 33 | [string]$WorkSpaceName 34 | ) 35 | 36 | Begin{ 37 | 38 | $schema = Get-AzureRmOperationalInsightsSchema -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkSpaceName 39 | $schemas = $schema.Value 40 | } 41 | Process{ 42 | $obj = @() 43 | ForEach($schema in $schemas) 44 | { 45 | $owners = $schema | Select-Object -ExpandProperty OwnerType 46 | ForEach ($owner in $owners) 47 | { 48 | $Properties = @{ 49 | DisplayName = $schema.DisplayName 50 | Type = $schema.Type 51 | Indexed = $schema.Indexed 52 | Stored = $schema.Stored 53 | Facet = $schema.Facet 54 | OwnerType = $owner 55 | } 56 | $obj += @(New-Object -TypeName PSCustomObject -Property $Properties) 57 | } 58 | } 59 | } 60 | 61 | End{ 62 | Write-Output $obj #| Sort-Object OwnerType 63 | } 64 | } -------------------------------------------------------------------------------- /Azure/OMS/Send-OMSSample1.ps1: -------------------------------------------------------------------------------- 1 | #((get-date).ToUniversalTime()).ToString("yyyy-MM-ddThh:mm:ss.fffZ") 2 | #Get-AzureRmOperationalInsightsWorkspace 3 | 4 | #$OMSWorkspacename = "AlexVerboonOMS" 5 | 6 | #OMS workspace Name 7 | $OMSWorkspacename = "APIDemo" 8 | 9 | # identify ResourceGroup Name 10 | $resourcegroupname = (Get-AzureRmOperationalInsightsWorkspace | Where-Object {$_.Name -eq "$OMSWorkspacename"}).ResourceGroupName 11 | 12 | # Workspace ID 13 | $customerId = (Get-AzureRmOperationalInsightsWorkspace | Where-Object {$_.Name -eq "$OMSWorkspaceName"}).CustomerId.guid 14 | 15 | # Primary Shared Key 16 | $sharedKey = (Get-AzureRmOperationalInsightsWorkspaceSharedKeys -ResourceGroupName $resourcegroupname -Name $OMSWorkspacename).PrimarySharedKey 17 | 18 | 19 | # Specify the name of the record type that you'll be creating 20 | $LogType = "MyComputers" 21 | 22 | # Specify a field with the created time for the records 23 | $TimeStampField = "DateValue" 24 | 25 | 26 | <# 27 | # Create two records with the same set of properties to create 28 | $json = @" 29 | [{ 30 | "MyComputerName": "Computer20", 31 | "MyModel": "Latitude1", 32 | "MyManufacturer": "Dell", 33 | "MyLocation": "Utrecht" 34 | 35 | }, 36 | { 37 | "MyComputerName": "Computer21", 38 | "MyModel": "Latitude2", 39 | "MyManufacturer": "Dell", 40 | "MyLocation": "Rotterdam" 41 | }, 42 | { 43 | "MyComputerName": "Computer22", 44 | "MyModel": "Tecra", 45 | "MyManufacturer": "Toshiba", 46 | "MyLocation": "Paris" 47 | }] 48 | "@ 49 | 50 | #> 51 | 52 | 53 | # Create two records with the same set of properties to create 54 | $json = @" 55 | [{ 56 | "MyComputerName": "Computer10", 57 | "MyModel": "T460", 58 | "MyManufacturer": "Lenovo", 59 | "MyLocation": "Zurich", 60 | "DateValue": "2017-02-08T12:13:35.576Z" 61 | }, 62 | { 63 | "MyComputerName": "Computer11", 64 | "MyModel": "T450", 65 | "MyManufacturer": "Lenovo", 66 | "MyLocation": "Amsterdam", 67 | "DateValue": "2017-02-08T12:13:35.576Z" 68 | }, 69 | { 70 | "MyComputerName": "Computer12", 71 | "MyModel": "T470", 72 | "MyManufacturer": "Lenovo", 73 | "MyLocation": "London", 74 | "DateValue": "2017-02-08T12:13:35.576Z" 75 | }] 76 | "@ 77 | 78 | 79 | 80 | 81 | # Create the function to create the authorization signature 82 | Function Build-Signature ($customerId, $sharedKey, $date, $contentLength, $method, $contentType, $resource) 83 | { 84 | $xHeaders = "x-ms-date:" + $date 85 | $stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource 86 | 87 | $bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash) 88 | $keyBytes = [Convert]::FromBase64String($sharedKey) 89 | 90 | $sha256 = New-Object System.Security.Cryptography.HMACSHA256 91 | $sha256.Key = $keyBytes 92 | $calculatedHash = $sha256.ComputeHash($bytesToHash) 93 | $encodedHash = [Convert]::ToBase64String($calculatedHash) 94 | $authorization = 'SharedKey {0}:{1}' -f $customerId,$encodedHash 95 | return $authorization 96 | } 97 | 98 | 99 | # Create the function to create and post the request 100 | Function Post-OMSData($customerId, $sharedKey, $body, $logType) 101 | { 102 | $method = "POST" 103 | $contentType = "application/json" 104 | $resource = "/api/logs" 105 | $rfc1123date = [DateTime]::UtcNow.ToString("r") 106 | $contentLength = $body.Length 107 | $signature = Build-Signature ` 108 | -customerId $customerId ` 109 | -sharedKey $sharedKey ` 110 | -date $rfc1123date ` 111 | -contentLength $contentLength ` 112 | -fileName $fileName ` 113 | -method $method ` 114 | -contentType $contentType ` 115 | -resource $resource 116 | $uri = "https://" + $customerId + ".ods.opinsights.azure.com" + $resource + "?api-version=2016-04-01" 117 | 118 | $headers = @{ 119 | "Authorization" = $signature; 120 | "Log-Type" = $logType; 121 | "x-ms-date" = $rfc1123date; 122 | "time-generated-field" = $TimeStampField; 123 | } 124 | 125 | $response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $body -UseBasicParsing 126 | return $response.StatusCode 127 | 128 | } 129 | 130 | # Submit the data to the API endpoint 131 | Post-OMSData -customerId $customerId -sharedKey $sharedKey -body ([System.Text.Encoding]::UTF8.GetBytes($json)) -logType $logType 132 | 133 | 134 | # Verify that the data is visible in OMS 135 | 136 | 137 | <# 138 | $dynamicQuery = "* Type=MyComputers_CL" 139 | $result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $ResourceGroupName -WorkspaceName $OMSWorkspacename -Query $dynamicQuery -Top 100 140 | $result.Value | ConvertFrom-Json 141 | #> 142 | -------------------------------------------------------------------------------- /Azure/OMS/Test-connectivity.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | # OMS Device Health connectivity test 4 | 5 | # Test as user 6 | 7 | $endPoints = @( 8 | 'v10.vortex-win.data.microsoft.com' 9 | 'settings-win.data.microsoft.com' 10 | 'watson.telemetry.microsoft.com' 11 | 'oca.telemetry.microsoft.com' 12 | 'vortex.data.microsoft.com' 13 | ) 14 | 15 | $endPoints | %{ Test-NetConnection -ComputerName $_ -Port 443 -ErrorAction Continue } | Select-Object -Property ComputerName,TcpTestSucceeded 16 | 17 | # Test as system 18 | [scriptblock]$accessTest = { 19 | $endPoints = @( 20 | 'v10.vortex-win.data.microsoft.com' 21 | 'settings-win.data.microsoft.com' 22 | 'watson.telemetry.microsoft.com' 23 | 'oca.telemetry.microsoft.com' 24 | 'vortex.data.microsoft.com' 25 | ) 26 | 27 | $endPoints | %{ Test-NetConnection -ComputerName $_ -Port 443 -ErrorAction Continue } | Select-Object -Property ComputerName,TcpTestSucceeded 28 | } 29 | 30 | $scriptFullPath = Join-Path $env:ProgramData "TestAccessToMicrosoftEndpoints.ps1" 31 | $outputFileFullPath = Join-Path $env:ProgramData "TestAccessToMicrosoftEndpoints_Output.txt" 32 | $accessTest.ToString() > $scriptFullPath 33 | $null > $outputFileFullPath 34 | $taskAction = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-ExecutionPolicy Bypass -Command `"&{$scriptFullPath > $outputFileFullPath}`"" 35 | $taskTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Addseconds(10) 36 | $task = Register-ScheduledTask -User 'NT AUTHORITY\SYSTEM' -TaskName 'MicrosoftTelemetryAccessTest' -Trigger $taskTrigger -Action $taskAction -Force 37 | Start-Sleep -Seconds 120 38 | Unregister-ScheduledTask -TaskName $task.TaskName -Confirm:$false 39 | Get-Content $outputFileFullPath -------------------------------------------------------------------------------- /Azure/OMS/UpgradeAnalytics/GetWindowsUpgradeAnalyticsdata.ps1: -------------------------------------------------------------------------------- 1 | # This script contains some examples how to retrieve Windows Upgrade Analytics data 2 | # that is stored in OMS 3 | 4 | # I used the guidance provided here: 5 | # https://blogs.technet.microsoft.com/privatecloud/2016/04/05/using-the-oms-search-api-with-native-powershell-cmdlets/ 6 | 7 | # Module Installation instructions, if not installed yet. 8 | # Install OMS PowerShell Module 9 | # Find-Module AzureRM.OperationalInsights | Install-Module 10 | # Install-Module AzureRM.OperationalInsights -Scope AllUsers 11 | # Get-Module AzureRm.OperationalInsights 12 | 13 | # Find OMS Workspaces 14 | Find-AzureRmResource -ResourceType "Microsoft.OperationalInsights/workspaces" 15 | 16 | #$ResourceGroupName = "mms-weu" 17 | #$WorkSpaceName = "AlexVerboonOMS" 18 | 19 | $ResourceGroupName = "RG-OMSWorkplace" 20 | $WorkSpaceName = "OMSWorkplace" 21 | 22 | # Get Saved Searches 23 | $query = Get-AzureRmOperationalInsightsSavedSearch ` 24 | -ResourceGroupName $ResourceGroupName ` 25 | -WorkspaceName $WorkSpaceName 26 | $query.value |FL 27 | 28 | $query = Get-AzureRmOperationalInsightsSavedSearch ` 29 | -ResourceGroupName $ResourceGroupName ` 30 | -WorkspaceName $WorkSpaceName ` 31 | -SavedSearchId "test|Drivers" 32 | $query.properties | FL 33 | 34 | # saved search 1 35 | $result = Get-AzureRmOperationalInsightsSavedSearchResults ` 36 | -ResourceGroupName $ResourceGroupName ` 37 | -WorkspaceName $WorkSpaceName ` 38 | -SavedSearchId "test|upgra_search1" 39 | $Apps = $result.value | ConvertFrom-Json 40 | 41 | # saved search 2 42 | $result = Get-AzureRmOperationalInsightsSavedSearchResults ` 43 | -ResourceGroupName $ResourceGroupName ` 44 | -WorkspaceName $WorkSpaceName ` 45 | -SavedSearchId "test|Drivers" 46 | $Drivers = $result.value | ConvertFrom-Json 47 | 48 | # A custom query 49 | $dynamicQuery = "* Type=MyComputers_CL" 50 | $result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkSpaceName -Query $dynamicQuery -Top 100 51 | $result.Value | ConvertFrom-Json 52 | 53 | $dynamicQuery = "* Type=MyData1_CL" 54 | $result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkSpaceName -Query $dynamicQuery -Top 100 55 | $result.Value | ConvertFrom-Json 56 | 57 | $dynamicQuery = "AlexComputerInfo_CL" 58 | $result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkSpaceName -Query $dynamicQuery -Top 100 59 | $result.Value | ConvertFrom-Json 60 | 61 | $dynamicQuery = "" 62 | 63 | $schema = Get-AzureRmOperationalInsightsSchema -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkSpaceName 64 | $schemas = $schema.Value #| Select-Object Name| Sort-Object Name 65 | 66 | 67 | $datainfo = @() 68 | ForEach($s in $schemas) 69 | { 70 | $dynamicQuery = "$($s.name)=*" 71 | $result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkSpaceName -Query $dynamicQuery -Top 10 72 | $hasdata = $result.Value | ConvertFrom-Json 73 | If ($hasdata -eq $null) 74 | { 75 | write-host "class $($s.name) has no log data" -ForegroundColor DarkGreen 76 | } 77 | Else 78 | { 79 | write-host "class $($s.name) contains log data" -ForegroundColor Green 80 | $datainfo += "$($s.Name)" 81 | } 82 | } 83 | $datainfo 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /Azure/OMS/eventreferene.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-ASCDataCollectionEventDetails{ 3 | 4 | <# 5 | .SYNOPSIS 6 | Get-ASCDataCollectionEventDetails 7 | 8 | .DESCRIPTION 9 | Get-ASCDataCollectionEventDetails retrieves Event information based 10 | on a provided set of EventIDs 11 | 12 | .PARAMETER Scope 13 | Minimum or Common 14 | 15 | .EXAMPLE 16 | Get-ASCDataCollectionEventDetails -Scope Minimal -Verbose 17 | 18 | Lists all Event IDs and Event information for the Minimal scope 19 | 20 | .NOTES 21 | https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/appendix-l--events-to-monitor 22 | https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/advanced-security-audit-policy-settings 23 | https://docs.microsoft.com/en-us/azure/security-center/security-center-enable-data-collection#data-collection-tier 24 | #> 25 | 26 | 27 | [CmdLetBinding()] 28 | Param( 29 | [Parameter(Mandatory=$true,Position=1)] 30 | [ValidateSet('Minimal',"Common")] 31 | [string]$Scope 32 | ) 33 | 34 | Begin{ 35 | 36 | # Events Inculded in "minimal" data collection 37 | $Minimal = ("1102","4624","4625","4657","4663","4688","4700","4702","4719","4720","4722","4723","4724","4727","4728","4732","4735","4737","4739","4740","4754","4755","4756","4767","4799","4825","4946","4948","4956","5024","5033","8001","8002","8003","8004","8005","8006","8007","8222") 38 | 39 | # Events Inculded in "Common" data collection 40 | $Common = ("1","299","300","324","340","403","404","410","411","412","413","431","500","501","1100","1102","1107","1108","4608","4610","4611","4614","461","4622", 41 | "4624","4625","4634","4647","4648","4649","4657","4661","4662","4663","4665","4666","4667","4688","4670","4672","4673","4674","4675","4689","4697", 42 | "4700","4702","4704","4705","4716","4717","4718","4719","4720","4722","4723","4724","4725","4726","4727","4728","4729","4733","4732","4735","4737", 43 | "4738","4739","4740","4742","4744","4745","4746","4750","4751","4752","4754","4755","4756","4757","4760","4761","4762","4764","4767","4768","4771", 44 | "4774","4778","4779","4781","4793","4797","4798","4799","4800","4801","4802","4803","4825","4826","4870","4886","4887","4888","4893","4898","4902", 45 | "4904","4905","4907","4931","4932","4933","4946","4948","4956","4985","5024","5033","5059","5136","5137","5140","5145","5632","6144","6145","6272", 46 | "6273","6278","6416","6423","6424","8001","8002","8003","8004","8005","8006","8007","8222","26401","30004") 47 | 48 | 49 | If ($Scope -eq "Minimal") 50 | { 51 | $EventScope = $Minimal 52 | } 53 | ElseIf($Scope -eq "Common") 54 | { 55 | $EventScope = $Common 56 | } 57 | } 58 | 59 | Process{ 60 | Write-Verbose "Processing Scope: $Scope" 61 | 62 | $EventIDReference = $null 63 | $EventLogProviders = "Microsoft-Windows-Security-Auditing","Microsoft-Windows-AppLocker","Microsoft-Windows-Security-Kerberos","Microsoft-Windows-eventlog","Microsoft-Windows-TaskScheduler","Microsoft-Windows-WinRM","Microsoft-Windows-WinLogon" 64 | ForEach ($entry in $EventLogProviders) 65 | { 66 | $EventIDList = (Get-Winevent -ListProvider $entry).events 67 | $EventIDList | Add-Member -MemberType NoteProperty -Name Provider -Value "$entry" 68 | $EventIDReference = $EventIDReference + $EventIDList 69 | } 70 | 71 | 72 | $Result = @() 73 | 74 | ForEach ($ScopeID in $EventScope) 75 | { 76 | Write-verbose "Processing EventID $ScopeID" 77 | $detail = $EventIDReference | Where-Object {$_.id -eq $ScopeID} 78 | 79 | If ([string]::IsNullOrEmpty($detail)) 80 | { 81 | $Found = $false 82 | $Detail = New-Object -TypeName PSObject 83 | $Detail | Add-Member -Name "ID" -Value $ScopeID -MemberType NoteProperty 84 | } 85 | Else 86 | { 87 | $Found = $true 88 | } 89 | 90 | ForEach ($detailentry in $detail) 91 | { 92 | $object = [ordered] @{ 93 | Id = $ScopeID 94 | Description = $detailentry.description 95 | ShortDesription = If([string]::IsNullOrEmpty($detailentry.Description)) {$null} Else {$detailentry.Description.split("`r`n")[0]} 96 | Level = $detailentry.Level.DisplayName 97 | LogLink = $detailentry.LogLink.DisplayName 98 | Provider = $detailentry.provider 99 | Found = $found 100 | } 101 | $Result += (New-Object -TypeName PSObject -Property $object) 102 | } 103 | } 104 | } 105 | 106 | End{ 107 | $Result 108 | } 109 | 110 | } 111 | 112 | 113 | -------------------------------------------------------------------------------- /Azure/OMS/eventsrc.txt: -------------------------------------------------------------------------------- 1 | // Microsoft.Sirona.DataCollectors.EventLogDataCollector 2 | private static readonly string[] WMI_SUPPORTED_LOG_NAMES = new string[] 3 | { 4 | "Application", 5 | "DFS Replication", 6 | "Directory Service", 7 | "DNS Server", 8 | "File Replication Service", 9 | "Forefront Identity Manager", 10 | "HardwareEvents", 11 | "Internet Explorer", 12 | "Key Management Service", 13 | "Security", 14 | "System", 15 | "Windows Azure", 16 | "Windows PowerShell", 17 | "Operations Manager" 18 | }; -------------------------------------------------------------------------------- /Azure/OMS/omsseclevel.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | $AllIDs = @() 4 | $test = @{} 5 | $secproviders = (Get-winevent -ListProvider *).name 6 | 7 | #$secproviders = "Microsoft-Windows-Security-Auditing" 8 | $secproviders = $secproviders + "Microsoft-Windows-AppLocker" 9 | 10 | $cnt = 1 11 | ForEach ($provider in $secproviders) 12 | { 13 | $ids = (Get-WinEvent -ListProvider $provider ).events 14 | ForEach ($id in $ids) 15 | { 16 | $object = [ordered] @{ 17 | Id = $id.Id 18 | Description = $id.description 19 | Provider = $provider 20 | Level = $id.Level.DisplayName 21 | LogLink = $id.LogLink.DisplayName 22 | } 23 | $AllIDs += (New-Object -TypeName PSObject -Property $object) 24 | $cnt++ 25 | } 26 | } 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Azure/README.md: -------------------------------------------------------------------------------- 1 | # My Azure Scripts 2 | Here's were I keep my Azure scripts. 3 | 4 | 5 | 6 | #Resource Manager 7 | This folder contains scripts and templates to deploy resources using Azure Resource Manager 8 | 9 | # Utilities 10 | ## Get-AzureImageSkuInfo.ps1 11 | The Get-AzureImageSkuInfo cmdlet retrieves all image SKUs available and n the offers from all publishers. 12 | 13 | Use this function to identify the parameter values required for the 14 | Set-AzureRmVMSourceImage cmdlet that is used when creating new Azure VMs 15 | using New-AzureRmVM. 16 | 17 | ## Get-AzureBlobInfo.ps1 18 | Get-AzureBlobInfo lists all blob content stored witin all or the specified 19 | storage account. 20 | 21 | ## Cleanup-AzureRmPublicIPAddress.ps1 22 | Use the Cleanup-AzureRmPublicIPAddress to remove Azure Public IP Addresses that 23 | are not linked to an existing Azure VirtualMachine based on the IPConfiguration 24 | data being empty. 25 | 26 | ## Cleanup-AzureRmNetworkInterfaces.ps1 27 | Use the Cleanup-AzureRmNetworkInterfaces to remove Azure Network Interfaces that 28 | are not linked to an existing Azure VirtualMachine. 29 | 30 | ##Cleanup-RmNetworkSecurityGroup.ps1 31 | Use the Cleanup-AzureRmSecurityGroup to remove Azure Network Security Groups that are not 32 | associated with any Subnet or Network interface being empty. 33 | 34 | # Other sources 35 | Manage Azure Virtual Machines using Resource Manager and PowerShell 36 | https://azure.microsoft.com/en-gb/documentation/articles/virtual-machines-windows-ps-manage/ 37 | 38 | 39 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/CustomScript/CustomScript1.ps1: -------------------------------------------------------------------------------- 1 | # Custom Script for Azure Resource Manager VM Deployment 2 | New-Item -Path C:\CustomScriptAlex -ItemType Directory -Force -ErrorAction SilentlyContinue 3 | 4 | 5 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/PostVMConfig/Set-VMPostConfig.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | function Set-VMPostConfiguration 4 | { 5 | <# 6 | .Synopsis 7 | Run Azure Windows VM Post Configuration 8 | .DESCRIPTION 9 | This script runs post configuration tasks on an Azure Windows VM. 10 | 11 | - Add BGInfo Extension 12 | - Join the client to the domain 13 | .PARAMETER VM 14 | The name of the Azure Virtual Machine 15 | 16 | .PARAMETER ResourceGroup 17 | The name of the Virtual Machine's Azure Resource group. 18 | 19 | .EXAMPLE 20 | Set-VMPostConfiguration -VM VM2 -ResourceGroup RG_2 21 | .NOTES 22 | 24.09.2016 by Alex Verboon 23 | #> 24 | 25 | [CmdletBinding()] 26 | Param 27 | ( 28 | # The Name of the Virtual Machine 29 | [Parameter(Mandatory=$true, 30 | ValueFromPipelineByPropertyName=$true, 31 | Position=0)] 32 | [string]$VM = "vm1" 33 | ) 34 | 35 | # The Name of the ResourceGroup 36 | DynamicParam { 37 |     $attributes = new-object System.Management.Automation.ParameterAttribute 38 |     $attributes.ParameterSetName = "__AllParameterSets" 39 |     $attributes.Mandatory = $true 40 |     $attributeCollection = 41 |       new-object -Type System.Collections.ObjectModel.Collection[System.Attribute] 42 |     $attributeCollection.Add($attributes) 43 |     $_Values = (Get-AzureRmResourceGroup).ResourceGroupName        44 |     $ValidateSet = 45 |       new-object System.Management.Automation.ValidateSetAttribute($_Values) 46 |     $attributeCollection.Add($ValidateSet) 47 |     $dynParam1 = 48 |       new-object -Type System.Management.Automation.RuntimeDefinedParameter( 49 |       "ResourceGroup", [string], $attributeCollection) 50 |     $paramDictionary = 51 |       new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary 52 |     $paramDictionary.Add("ResourceGroup", $dynParam1) 53 |     return $paramDictionary } 54 | 55 | Begin 56 | { 57 | $Location = "westeurope" 58 | $ResourceGroup = "RG_2" 59 | $Domain = "corp.contoso.com" 60 | 61 | $djoinaccount = Get-Credential 62 | 63 | $DomainINfo = @{ 64 | "Name" = "$Domain"; 65 | "User" = $djoinaccount.Username; 66 | "Restart" = "false"; 67 | "Options" = "3"; 68 | "OUPath" = "" 69 | } 70 | $DomainINfo = $DomainINfo | ConvertTo-Json 71 | 72 | $Password = @{ 73 | "Password" = $djoinaccount.GetNetworkCredential().password 74 | } 75 | $Password = $Password | ConvertTo-Json 76 | 77 | } 78 | Process 79 | { 80 | # Set BGInfo Extension 81 | Set-AzureRmVMExtension -ResourceGroupName $ResourceGroup -VMName "$VM" -ExtensionType "BGInfo" -Name "BGInfo" -Publisher "Microsoft.Compute" -TypeHandlerVersion "2.1" -Location $Location 82 | # Join VM to domain 83 | Set-AzureRmVMExtension -ResourceGroupName $ResourceGroup -VMName "$VM" -ExtensionType "JsonADDomainExtension" -Name "joindomain" -Publisher "Microsoft.Compute" -TypeHandlerVersion "1.0" -Location $Location -SettingString $DomainINfo -ProtectedSettingString $Password 84 | 85 | # WinRM 86 | #https://github.com/Azure/azure-quickstart-templates/tree/3c9980dd6baf21e84e48fcc9028ee54b3c0269f6/201-vm-winrm-windows 87 | 88 | 89 | 90 | 91 | 92 | } 93 | End 94 | { 95 | 96 | } 97 | } 98 | 99 | 100 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/Template_Win10_1/Deploy_VM.ps1: -------------------------------------------------------------------------------- 1 |  2 | $ResourceGroupName = "RG_3" 3 | 4 | #New-AzureRmResourceGroup -Name $ResourceGroupName -Location "westeurope" -Tag @{Company="FooCorp"} 5 | 6 | 7 | $vmname = "vm14" 8 | $Templatefile = "C:\Data\dev\posh\Azure\ResourceManager\VirtualMachine\Template_Win10_1\template.json" 9 | 10 | 11 | $parameters = @{"location"="westeurope"; 12 | "virtualMachineName" = "$vmname"; 13 | "virtualMachineSize" = "Basic_A2"; 14 | "adminUsername" = "Master_Admin"; 15 | "adminPassword" = "Access4theAdmin"; 16 | "storageAccountName" = "rg11099"; 17 | "virtualNetworkName" = "VNet1"; 18 | "networkInterfaceName" = "ni_$vmname" 19 | "networkSecurityGroupName" = "$vmname-nsg"; 20 | "subnetName" = "Subnet-1"; 21 | "publicIpAddressName" = "$vmname-ip"; 22 | "publicIpAddressType" = "Dynamic"; 23 | } 24 | 25 | 26 | $TestTempl = Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateFile $TemplateFile -TemplateParameterObject $parameters -Verbose 27 | 28 | New-AzureRmResourceGroupDeployment -Name "Deployvm$vmname" -ResourceGroupName $ResourceGroupName -TemplateFile $TemplateFile -TemplateParameterObject $parameters -Verbose -DeploymentDebugLogLevel All 29 | 30 | 31 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Sources 5 | Using Custom Script extension With Azure Resource Manager templates 6 | https://github.com/Azure/azure-content/blob/master/articles/virtual-machines/virtual-machines-extensions-customscript-with-template.md 7 | 8 | 9 | https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-windows-infrastructure-resource-groups-guidelines/ 10 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/vm10 template/DEPLOY_TEST.ps1: -------------------------------------------------------------------------------- 1 |  2 | $ResourceGroupName = "RG_2" 3 | 4 | $parameters = @{"location"="westeurope"; 5 | "virtualMachineName" = "VM11"; 6 | "virtualMachineSize" = "Basic_A2"; 7 | "adminUsername" = "Master_Admin"; 8 | "adminPassword" = "Access4theAdmin"; 9 | "storageAccountName" = "rg11099"; 10 | "virtualNetworkName" = "VNet1"; 11 | "networkInterfaceName" = "vm11558" 12 | "networkSecurityGroupName" = "vm10-nsg"; 13 | #"diagnosticsStorageAccountName" = "rg11099" 14 | #"diagnosticsStorageAccountId" = "/subscriptions/fac764d2-d579-41e0-ba9d-d787cf339faf/resourceGroups/rg_1/providers/Microsoft.Storage/storageAccounts/rg11099"; 15 | "subnetName" = "Subnet-1"; 16 | "publicIpAddressName" = "vm11-ip"; 17 | "publicIpAddressType" = "Dynamic"; 18 | } 19 | 20 | $Templatefile = "C:\Data\dev\posh\Azure\ResourceManager\VirtualMachine\vm10 template\template.json" 21 | Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateFile $TemplateFile -TemplateParameterObject $parameters -Verbose 22 | 23 | New-AzureRmResourceGroupDeployment -Name "Deployvm02" -ResourceGroupName $ResourceGroupName -TemplateFile $TemplateFile -TemplateParameterObject $parameters -Verbose 24 | 25 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/vm10 template/DEPLOY_VM.ps1: -------------------------------------------------------------------------------- 1 |  2 | $ResourceGroupName = "RG_2" 3 | 4 | # Variables for Template and Template parameter file 5 | $Templatefile = "C:\Data\dev\posh\Azure\ResourceManager\VirtualMachine\vm10 template\template.json" 6 | $ParameterFile = "C:\Data\dev\posh\Azure\ResourceManager\VirtualMachine\vm10 template\parameters.json" 7 | 8 | 9 | # Create Resource Group 10 | #$ResourceGroupName = "RG_2" 11 | #$Location = "westeurope" 12 | #New-AzureRmResourceGroup -Name $ResourceGroupName -Location $location -Verbose 13 | 14 | 15 | Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateFile $TemplateFile -TemplateParameterFile $ParameterFile -Verbose 16 | #New-AzureRmResourceGroupDeployment -Name "Deployvm_01" -ResourceGroupName $ResourceGroupName -TemplateFile $TemplateFile -TemplateParameterFile $ParameterFile -Verbose 17 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/vm10 template/deploy.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Deploys a template to Azure 4 | 5 | .DESCRIPTION 6 | Deploys an Azure Resource Manager template 7 | 8 | .PARAMETER subscriptionId 9 | The subscription id where the template will be deployed. 10 | 11 | .PARAMETER resourceGroupName 12 | The resource group where the template will be deployed. Can be the name of an existing or a new resource group. 13 | 14 | .PARAMETER resourceGroupLocation 15 | Optional, a resource group location. If specified, will try to create a new resource group in this location. If not specified, assumes resource group is existing. 16 | 17 | .PARAMETER deploymentName 18 | The deployment name. 19 | 20 | .PARAMETER templateFilePath 21 | Optional, path to the template file. Defaults to template.json. 22 | 23 | .PARAMETER parametersFilePath 24 | Optional, path to the parameters file. Defaults to parameters.json. If file is not found, will prompt for parameter values based on template. 25 | #> 26 | 27 | param( 28 | [Parameter(Mandatory=$True)] 29 | [string] 30 | $subscriptionId, 31 | 32 | [Parameter(Mandatory=$True)] 33 | [string] 34 | $resourceGroupName, 35 | 36 | [string] 37 | $resourceGroupLocation, 38 | 39 | [Parameter(Mandatory=$True)] 40 | [string] 41 | $deploymentName, 42 | 43 | [string] 44 | $templateFilePath = "template.json", 45 | 46 | [string] 47 | $parametersFilePath = "parameters.json" 48 | ) 49 | 50 | <# 51 | .SYNOPSIS 52 | Registers RPs 53 | #> 54 | Function RegisterRP { 55 | Param( 56 | [string]$ResourceProviderNamespace 57 | ) 58 | 59 | Write-Host "Registering resource provider '$ResourceProviderNamespace'"; 60 | Register-AzureRmResourceProvider -ProviderNamespace $ResourceProviderNamespace -Force; 61 | } 62 | 63 | #****************************************************************************** 64 | # Script body 65 | # Execution begins here 66 | #****************************************************************************** 67 | $ErrorActionPreference = "Stop" 68 | 69 | # sign in 70 | Write-Host "Logging in..."; 71 | Login-AzureRmAccount; 72 | 73 | # select subscription 74 | Write-Host "Selecting subscription '$subscriptionId'"; 75 | Select-AzureRmSubscription -SubscriptionID $subscriptionId; 76 | 77 | # Register RPs 78 | $resourceProviders = @("microsoft.compute","microsoft.network"); 79 | if($resourceProviders.length) { 80 | Write-Host "Registering resource providers" 81 | foreach($resourceProvider in $resourceProviders) { 82 | RegisterRP($resourceProvider); 83 | } 84 | } 85 | 86 | #Create or check for existing resource group 87 | $resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue 88 | if(!$resourceGroup) 89 | { 90 | Write-Host "Resource group '$resourceGroupName' does not exist. To create a new resource group, please enter a location."; 91 | if(!$resourceGroupLocation) { 92 | $resourceGroupLocation = Read-Host "resourceGroupLocation"; 93 | } 94 | Write-Host "Creating resource group '$resourceGroupName' in location '$resourceGroupLocation'"; 95 | New-AzureRmResourceGroup -Name $resourceGroupName -Location $resourceGroupLocation 96 | } 97 | else{ 98 | Write-Host "Using existing resource group '$resourceGroupName'"; 99 | } 100 | 101 | # Start the deployment 102 | Write-Host "Starting deployment..."; 103 | if(Test-Path $parametersFilePath) { 104 | New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile $templateFilePath -TemplateParameterFile $parametersFilePath; 105 | } else { 106 | New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile $templateFilePath; 107 | } -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/vm10 template/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | usage() { echo "Usage: $0 -t -p -q -l " 1>&2; exit 1; } 4 | 5 | # Initialize parameters specified from command line 6 | while getopts ":t:p:q:l:" o; do 7 | case "${o}" in 8 | t) 9 | echo "in case t" 10 | subscriptionId=${OPTARG} 11 | ;; 12 | p) 13 | resourceGroupName=${OPTARG} 14 | ;; 15 | q) 16 | deploymentName=${OPTARG} 17 | ;; 18 | l) 19 | resourceGroupLocation=${OPTARG} 20 | ;; 21 | esac 22 | done 23 | shift $((OPTIND-1)) 24 | 25 | #Prompt for parameters is some required parameters are missing 26 | if [ -z "$subscriptionId" ]; then 27 | echo "Subscription Id:" 28 | read subscriptionId 29 | fi 30 | 31 | if [ -z "$resourceGroupName" ]; then 32 | echo "ResourceGroupName:" 33 | read resourceGroupName 34 | fi 35 | 36 | if [ -z "$deploymentName" ]; then 37 | echo "DeploymentName:" 38 | read deploymentName 39 | fi 40 | 41 | if [ -z "$resourceGroupLocation" ]; then 42 | echo "Enter a location below to create a new resource group else skip this" 43 | echo "ResourceGroupLocation:" 44 | read resourceGroupLocation 45 | fi 46 | 47 | #templateFile Path - template file to be used 48 | templateFilePath="template.json" 49 | 50 | #parameter file path 51 | parametersFilePath="parameters.json" 52 | 53 | if [ -z "$subscriptionId" ] || [ -z "$resourceGroupName" ] || [ -z "$deploymentName" ]; then 54 | echo "Either one of subscriptionId, resourceGroupName, deploymentName is empty" 55 | usage 56 | fi 57 | 58 | #login to azure using your credentials 59 | azure login 60 | 61 | #set the default subscription id 62 | azure account set $subscriptionId 63 | 64 | #switch the mode to azure resource manager 65 | azure config mode arm 66 | 67 | #Check for existing resource group 68 | if [ -z "$resourceGroupLocation" ] ; 69 | then 70 | echo "Using existing resource group..." 71 | else 72 | echo "Creating a new resource group..." 73 | azure group create --name $resourceGroupName --location $resourceGroupLocation 74 | fi 75 | 76 | #Start deployment 77 | echo "Starting deployment..." 78 | azure group deployment create --name $deploymentName --resource-group $resourceGroupName --template-file $templateFilePath --parameters-file $parametersFilePath -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/vm10 template/deployer.rb: -------------------------------------------------------------------------------- 1 | require 'azure_mgmt_resources' 2 | 3 | class Deployer 4 | 5 | # Initialize the deployer class with subscription, resource group and resource group location. The class will raise an 6 | # ArgumentError if there are empty values for Tenant Id, Client Id or Client Secret environment variables. 7 | # 8 | # @param [String] subscription_id the subscription to deploy the template 9 | # @param [String] resource_group the resource group to create or update and then deploy the template 10 | # @param [String] resource_group_location the location of the resource group 11 | def initialize(subscription_id, resource_group, resource_group_location) 12 | raise ArgumentError.new("Missing template file 'template.json' in current directory.") unless File.exist?('template.json') 13 | raise ArgumentError.new("Missing parameters file 'parameters.json' in current directory.") unless File.exist?('parameters.json') 14 | @resource_group = resource_group 15 | @subscription_id = subscription_id 16 | @resource_group_location = resource_group_location 17 | provider = MsRestAzure::ApplicationTokenProvider.new( 18 | ENV['AZURE_TENANT_ID'], 19 | ENV['AZURE_CLIENT_ID'], 20 | ENV['AZURE_CLIENT_SECRET']) 21 | credentials = MsRest::TokenCredentials.new(provider) 22 | @client = Azure::ARM::Resources::ResourceManagementClient.new(credentials) 23 | @client.subscription_id = @subscription_id 24 | end 25 | 26 | # Deploy the template to a resource group 27 | def deploy 28 | # ensure the resource group is created 29 | params = Azure::ARM::Resources::Models::ResourceGroup.new.tap do |rg| 30 | rg.location = @resource_group_location 31 | end 32 | @client.resource_groups.create_or_update_async(@resource_group, params).value! 33 | 34 | # build the deployment from a json file template from parameters 35 | template = File.read(File.expand_path(File.join(__dir__, 'template.json'))) 36 | deployment = Azure::ARM::Resources::Models::Deployment.new 37 | deployment.properties = Azure::ARM::Resources::Models::DeploymentProperties.new 38 | deployment.properties.template = JSON.parse(template) 39 | deployment.properties.mode = Azure::ARM::Resources::Models::DeploymentMode::Incremental 40 | 41 | # build the deployment template parameters from Hash to {key: {value: value}} format 42 | deploy_params = File.read(File.expand_path(File.join(__dir__, 'parameters.json'))) 43 | deployment.properties.parameters = JSON.parse(deploy_params)["parameters"] 44 | 45 | # put the deployment to the resource group 46 | @client.deployments.create_or_update(@resource_group, 'azure-sample', deployment).value!.body 47 | end 48 | end 49 | 50 | # Get user inputs and execute the script 51 | if(ARGV.empty?) 52 | puts "Please specify subscriptionId resourceGroupName resourceGroupLocation as command line arguments" 53 | exit 54 | end 55 | 56 | subscription_id = ARGV[0] # Azure Subscription Id 57 | resource_group = ARGV[1] # The resource group for deployment 58 | resource_group_location = ARGV[2] # The resource group location 59 | 60 | msg = "\nInitializing the Deployer class with subscription id: #{subscription_id}, resource group: #{resource_group}" 61 | msg += "\nand resource group location: #{resource_group_location}...\n\n" 62 | puts msg 63 | 64 | # Initialize the deployer class 65 | deployer = Deployer.new(subscription_id, resource_group, resource_group_location) 66 | 67 | puts "Beginning the deployment... \n\n" 68 | # Deploy the template 69 | deployment = deployer.deploy 70 | 71 | puts "Done deploying!!" -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualMachine/vm10 template/parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#", 3 | "contentVersion": "1.0.0.0", 4 | "parameters": { 5 | "location": { 6 | "value": "westeurope" 7 | }, 8 | "virtualMachineName": { 9 | "value": "vm10" 10 | }, 11 | "virtualMachineSize": { 12 | "value": "Basic_A2" 13 | }, 14 | "adminUsername": { 15 | "value": "Master_Admin" 16 | }, 17 | "storageAccountName": { 18 | "value": "rg11099" 19 | }, 20 | "virtualNetworkName": { 21 | "value": "VNet1" 22 | }, 23 | "networkInterfaceName": { 24 | "value": "vm10558" 25 | }, 26 | "networkSecurityGroupName": { 27 | "value": "vm10-nsg" 28 | }, 29 | "adminPassword": { 30 | "value": "Access4theAdmin" 31 | }, 32 | "diagnosticsStorageAccountName": { 33 | "value": "rg11099" 34 | }, 35 | "diagnosticsStorageAccountId": { 36 | "value": "/subscriptions/fac764d2-d579-41e0-ba9d-d787cf339faf/resourceGroups/rg_1/providers/Microsoft.Storage/storageAccounts/rg11099" 37 | }, 38 | "subnetName": { 39 | "value": "Subnet-1" 40 | }, 41 | "publicIpAddressName": { 42 | "value": "vm10-ip" 43 | }, 44 | "publicIpAddressType": { 45 | "value": "Dynamic" 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualNetwork/azuredeploy_virtualnetwork.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", 3 | "contentVersion": "1.0.0.0", 4 | "parameters": { 5 | "vnetName": { 6 | "type": "string", 7 | "defaultValue": "VNet1", 8 | "metadata": { 9 | "description": "VNet name" 10 | } 11 | } 12 | }, 13 | "variables": { 14 | "VN_1Prefix": "10.0.0.0/16", 15 | "VN_1Subnet1Name": "Subnet-1", 16 | "VN_1Subnet1Prefix": "10.0.0.0/24", 17 | "VN_1Subnet2Name": "Subnet-2", 18 | "VN_1Subnet2Prefix": "10.0.1.0/24" 19 | }, 20 | "resources": [ 21 | { 22 | "name": "[parameters('vnetName')]", 23 | "type": "Microsoft.Network/virtualNetworks", 24 | "location": "[resourceGroup().location]", 25 | "apiVersion": "2015-06-15", 26 | "dependsOn": [ ], 27 | "tags": { 28 | "displayName": "[parameters('vnetName')]" 29 | }, 30 | "properties": { 31 | "addressSpace": { 32 | "addressPrefixes": [ 33 | "[variables('VN_1Prefix')]" 34 | ] 35 | }, 36 | "subnets": [ 37 | { 38 | "name": "[variables('VN_1Subnet1Name')]", 39 | "properties": { 40 | "addressPrefix": "[variables('VN_1Subnet1Prefix')]" 41 | } 42 | }, 43 | { 44 | "name": "[variables('VN_1Subnet2Name')]", 45 | "properties": { 46 | "addressPrefix": "[variables('VN_1Subnet2Prefix')]" 47 | } 48 | } 49 | ] 50 | } 51 | } 52 | ], 53 | "outputs": { 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualNetwork/azuredeploy_virtualnetwork.parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#", 3 | "contentVersion": "1.0.0.0", 4 | "parameters": { 5 | 6 | "vnetName" : { "value": "Vnet2"} 7 | } 8 | } -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualNetwork/new-virtualnetwork.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | # Login to Azure 5 | Try{ 6 | $checkifconnected =Get-AzureRmVMImagePublisher -Location $location 7 | } 8 | Catch{ 9 | # okay looks liek we're not yet connected 10 | Login-AzureRmAccount 11 | $checkifconnected =Get-AzureRmVMImagePublisher -Location $location 12 | } 13 | 14 | 15 | # Variables for Template and Template parameter file 16 | $Templatefile = "https://raw.githubusercontent.com/alexverboon/posh/master/Azure/ResourceManager/VirtualNetwork/azuredeploy_virtualnetwork.json" 17 | $ParameterFile = "https://raw.githubusercontent.com/alexverboon/posh/master/Azure/ResourceManager/VirtualNetwork/azuredeploy_virtualnetwork.parameters.json" 18 | 19 | # Input Object 20 | $paramobj = @{ vnetname = "Vnet3"} 21 | 22 | # Create Resource Group 23 | $ResourceGroupName = "TestResourceGroup" 24 | $Location = "westeurope" 25 | New-AzureRmResourceGroup -Name $ResourceGroupName -Location $location -Verbose 26 | 27 | 28 | 29 | # Let's test things first 30 | 31 | #Test with Template only 32 | Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateUri $TemplateFile -Verbose 33 | #Test with Template and parameter file 34 | Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateUri $TemplateFile -TemplateParameterUri $ParameterFile -Verbose 35 | #Test with template and parameter object 36 | Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateUri $TemplateFile -TemplateParameterObject $paramobj -Verbose 37 | 38 | 39 | #and now create virtual networks 40 | New-AzureRmResourceGroupDeployment -Name "Example1" -ResourceGroupName $ResourceGroupName -TemplateUri $TemplateFile -Verbose -Mode Complete 41 | New-AzureRmResourceGroupDeployment -Name "Example2" -ResourceGroupName $ResourceGroupName -TemplateUri $TemplateFile -TemplateParameterUri $ParameterFile -Verbose 42 | New-AzureRmResourceGroupDeployment -Name "Example3" -ResourceGroupName $ResourceGroupName -TemplateUri $TemplateFile -TemplateParameterObject $paramobj -Verbose 43 | 44 | # let's look at the Deployments 45 | Get-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName 46 | 47 | # now with complete mode 48 | New-AzureRmResourceGroupDeployment -Name "Example3" -ResourceGroupName $ResourceGroupName -TemplateUri $TemplateFile -TemplateParameterObject $paramobj -Mode Complete -Verbose 49 | -------------------------------------------------------------------------------- /Azure/ResourceManager/VirtualNetwork/readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexverboon/posh/6d6f28883b14bf62e89932b1ab209cbfba6768b5/Azure/ResourceManager/VirtualNetwork/readme.md -------------------------------------------------------------------------------- /Azure/Utilities/AzurePSVersion.ps1: -------------------------------------------------------------------------------- 1 | $name='Azure'  2 |   3 | if(Get-Module -ListAvailable |   4 |     Where-Object { $_.name -eq $name })   5 | {   6 |     (Get-Module -ListAvailable | Where-Object{ $_.Name -eq $name }) |   7 |     Select Version, Name, Author, PowerShellVersion  | Format-List;   8 | }   9 | else   10 | {   11 |     “The Azure PowerShell module is not installed.”  12 | } -------------------------------------------------------------------------------- /Azure/Utilities/Cleanup-AzureRmNetworkInterfaces.ps1: -------------------------------------------------------------------------------- 1 |  2 | function Cleanup-AzureRmNetworkInterfaces 3 | { 4 | <# 5 | .Synopsis 6 | Cleanup-AzureRmNetworkInterfaces removes Network Interfaces that are not linked 7 | to an Azure VirtualMachine 8 | .DESCRIPTION 9 | Use the Cleanup-AzureRmNetworkInterfaces to remove Azure Network Interfaces that 10 | are not linked to an existing Azure VirtualMachine. 11 | .PARAMETER ResourceGrup 12 | Specifies the name of the resource group from which network interfaces are 13 | to be retrieved. 14 | .PARAMETER ListOnly 15 | Only lists Azure Network Interfaces that are not linked to an existing Azure Virtual Machine 16 | 17 | .EXAMPLE 18 | Cleanup-AzureRmNetworkInterfaces -ResourceGroup RG_2 19 | .EXAMPLE 20 | Cleanup-AzureRmNetworkInterfaces -ResourceGroup RG_2 -ListOnly 21 | 22 | Name ResourceGuid 23 | ---- ------------ 24 | vm3872 7d17b843-e9fb-4838-bce5-428817a95037 25 | .NOTES 26 | Alex Verboon, version 1.0, 01.10.2016 27 | #> 28 | 29 | [CmdletBinding(SupportsShouldProcess=$true, 30 |    ConfirmImpact="High")] 31 | Param 32 | ( 33 | # Specifies the name of the resource group from which network interfaces are to be retrieved. 34 | [Parameter(Mandatory=$true, 35 | ValueFromPipelineByPropertyName=$true, 36 | Position=0)] 37 | [string]$ResourceGroup, 38 | # Only lists Azure Network Interfaces that are not linked to an existing Azure Virtual Machine 39 | [switch]$ListOnly 40 | ) 41 | Begin 42 | { 43 | If (AzureRmResourceGroup -Name $ResourceGroup -ErrorAction SilentlyContinue ) 44 | { 45 | $az_networkinterfaces = Get-AzureRmNetworkInterface -ResourceGroupName $ResourceGroup 46 | $RemAzNetworkInterface = $az_networkinterfaces | Where-Object {$_.VirtualMachine -eq $null} 47 | } 48 | Else 49 | { 50 | Write-Error "Provided resource group does not exist: $ResourceGroup" 51 | Throw 52 | } 53 | 54 | 55 | } 56 | Process 57 | { 58 | $removed = @() 59 | If ($PSBoundParameters.ContainsKey("ListOnly")) 60 | { 61 | $RemAzNetworkInterface | Select-Object Name,ResourceGuid 62 | } 63 | Else 64 | { 65 | ForEach($ni in $RemAzNetworkInterface) 66 | { 67 | if ($pscmdlet.ShouldProcess("Deleting NetworkInterface $($ni.Name)")) 68 | { 69 | Write-Output "Removing NetworkInterface without Virtual Machine association: $($ni.Name)" 70 |   Remove-AzureRmNetworkInterface -Name "$($ni.name)" -ResourceGroupName $ResourceGroup 71 | $object = New-Object -TypeName PSObject 72 | $object | Add-Member -MemberType NoteProperty -Name Name -Value $($ni.Name) 73 | $object | Add-Member -MemberType NoteProperty -Name ResourceGuid -Value $($ni.ResourceGuid) 74 | $removed += $object 75 | } 76 | } 77 | } 78 | } 79 | End 80 | { 81 | # List the removed objects 82 | $removed 83 | } 84 | } 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /Azure/Utilities/Cleanup-AzureRmPublicIPAddress.ps1: -------------------------------------------------------------------------------- 1 |  2 | function Cleanup-AzureRmPublicIPAddress 3 | { 4 | <# 5 | .Synopsis 6 | Cleanup-AzureRmPublicIPAddress removes Public IP Addresses that are not linked 7 | to an Azure VirtualMachine 8 | .DESCRIPTION 9 | Use the Cleanup-AzureRmPublicIPAddress to remove Azure Public IP Addresses that 10 | are not linked to an existing Azure VirtualMachine based on the IPConfiguration data 11 | being empty. 12 | .PARAMETER ResourceGrup 13 | Specifies the name of the resource group from which Public IP Addresses are 14 | to be retrieved. 15 | .PARAMETER ListOnly 16 | Only lists Azure Public IP Addresses that are not linked to an existing Azure Virtual Machine 17 | 18 | .EXAMPLE 19 | Cleanup-AzureRmPublicIPAddress -ResourceGroup RG_2 20 | .EXAMPLE 21 | Cleanup-AzureRmPublicIPAddress -ResourceGroup RG_2 -ListOnly 22 | 23 | Lists all Public IP Addresses that have no association to a virtual machine. 24 | 25 | Name ResourceGuid 26 | ---- ------------ 27 | vm01-ip b5c0f73b-abda-4a24-b3bd-2722b08aabe0 28 | VM2-ip f03360f2-887e-44fe-a5ad-396195cd8efc 29 | VM3-ip 5db8d1fa-f551-4794-a9c0-27cd005b4742 30 | .NOTES 31 | Alex Verboon, version 1.0, 01.10.2016 32 | #> 33 | 34 | [CmdletBinding(SupportsShouldProcess=$true, 35 |    ConfirmImpact="High")] 36 | Param 37 | ( 38 | # Specifies the name of the resource group from which Public IP Addresses are to be retrieved. 39 | [Parameter(Mandatory=$true, 40 | ValueFromPipelineByPropertyName=$true, 41 | Position=0)] 42 | [string]$ResourceGroup, 43 | # Only lists Azure Network Interfaces that are not linked to an existing Azure Virtual Machine 44 | [switch]$ListOnly 45 | ) 46 | Begin 47 | { 48 | If (AzureRmResourceGroup -Name $ResourceGroup -ErrorAction SilentlyContinue ) 49 | { 50 | $az_publicipaddress = Get-AzureRmPublicIpAddress -ResourceGroupName $ResourceGroup 51 | $RemAzPublicIP = $az_publicipaddress | Where-Object {$_.IpConfiguration -eq $null} 52 | } 53 | Else 54 | { 55 | Write-Error "Provided resource group does not exist: $ResourceGroup" 56 | Throw 57 | } 58 | } 59 | Process 60 | { 61 | $removed = @() 62 | If ($PSBoundParameters.ContainsKey("ListOnly")) 63 | { 64 | $RemAzPublicIP | Select-Object Name,ResourceGuid 65 | } 66 | Else 67 | { 68 | ForEach($pi in $RemAzPublicIP) 69 | { 70 | if ($pscmdlet.ShouldProcess("Deleting NetworkInterface $($pi.Name)")) 71 | { 72 | Write-Output "Removing Public IP Address without Virtual Machine association: $($pi.Name)" 73 |   Remove-AzureRmPublicIpAddress -Name "$($pi.name)" -ResourceGroupName $ResourceGroup 74 | $object = New-Object -TypeName PSObject 75 | $object | Add-Member -MemberType NoteProperty -Name Name -Value $($pi.Name) 76 | $object | Add-Member -MemberType NoteProperty -Name ResourceGuid -Value $($pi.ResourceGuid) 77 | $removed += $object 78 | } 79 | } 80 | } 81 | } 82 | End 83 | { 84 | # List the removed objects 85 | $removed 86 | } 87 | } 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /Azure/Utilities/Cleanup-RmNetworkSecurityGroup.ps1: -------------------------------------------------------------------------------- 1 |  2 | function Cleanup-RmNetworkSecurityGroup 3 | { 4 | <# 5 | .Synopsis 6 | Cleanup-AzureRmSecurityGroup removes Azure Network Security Groups that are not associated with 7 | a Subnet or a Network interface 8 | .DESCRIPTION 9 | Use the Cleanup-AzureRmSecurityGroup to remove Azure Network Security Groups that are not 10 | associated with any Subnet or Network interface 11 | being empty. 12 | .PARAMETER ResourceGrup 13 | Specifies the name of the resource group from which Public IP Addresses are 14 | to be retrieved. 15 | .PARAMETER ListOnly 16 | Only lists Azure Network Security Groups that are not associated with a subnet or network interface 17 | 18 | .EXAMPLE 19 | Cleanup-RmNetworkSecurityGroup -ResourceGroup RG_2 20 | 21 | .EXAMPLE 22 | Cleanup-RmNetworkSecurityGroup -ResourceGroup RG_2 -ListOnly 23 | 24 | Lists all Azure Network Security Groups that are not associated with a subnet or network interface 25 | 26 | 27 | .NOTES 28 | Alex Verboon, version 1.0, 01.10.2016 29 | #> 30 | 31 | [CmdletBinding(SupportsShouldProcess=$true, 32 |    ConfirmImpact="High")] 33 | Param 34 | ( 35 | # Specifies the name of the resource group from which Public IP Addresses are to be retrieved. 36 | [Parameter(Mandatory=$true, 37 | ValueFromPipelineByPropertyName=$true, 38 | Position=0)] 39 | [string]$ResourceGroup, 40 | # Only lists Azure Network Interfaces that are not linked to an existing Azure Virtual Machine 41 | [switch]$ListOnly 42 | ) 43 | Begin 44 | { 45 | If (AzureRmResourceGroup -Name $ResourceGroup -ErrorAction SilentlyContinue ) 46 | { 47 | 48 | $az_nsg = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $ResourceGroup 49 | $RemAzSecurityGroup = $az_nsg | Select-Object Name, Subnets,Networkinterfaces | Where-Object {$_.subnets.id -eq $null -and $_.networkinterfaces.id -eq $null} 50 | } 51 | Else 52 | { 53 | Write-Error "Provided resource group does not exist: $ResourceGroup" 54 | Throw 55 | } 56 | } 57 | Process 58 | { 59 | $removed = @() 60 | If ($PSBoundParameters.ContainsKey("ListOnly")) 61 | { 62 | $RemAzSecurityGroup | Select-Object Name 63 | } 64 | Else 65 | { 66 | ForEach($sg in $RemAzSecurityGroup) 67 | { 68 | if ($pscmdlet.ShouldProcess("Deleting NetworkInterface $($sg.Name)")) 69 | { 70 | Write-Output "Removing Azurer Network Security Group: $($sg.Name)" 71 |   Remove-AzureRmNetworkSecurityGroup -Name "$($sg.name)" -ResourceGroupName $ResourceGroup 72 | $object = New-Object -TypeName PSObject 73 | $object | Add-Member -MemberType NoteProperty -Name Name -Value $($sg.Name) 74 | $removed += $object 75 | } 76 | } 77 | } 78 | } 79 | End 80 | { 81 | # List the removed objects 82 | $removed 83 | } 84 | } 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /Azure/Utilities/Get-AzureBlobInfo.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-AzureBlobInfo 3 | { 4 | <# 5 | .Synopsis 6 | Get-AzureBlobInfo lists all blob content stored in Azure 7 | .DESCRIPTION 8 | Get-AzureBlobInfo lists all blob content stored witin all or the specified 9 | storage account. 10 | .EXAMPLE 11 | Get-AzureBlobInfo 12 | 13 | List all storage blobs stored within all available storage accounts 14 | 15 | .EXAMPLE 16 | Get-AzureBlobInfo -StorageAccountName rg2disks444 17 | 18 | List all storage blobs stored wtihin the storage account rg2disks444 19 | 20 | EXAMPLE 21 | Get-AzureBlobInfo | Select-Object Name,STorageaccount,LeaseStatus 22 | 23 | List all storage blobs and output the lease status 24 | 25 | .EXAMPLE 26 | Get-AzureBlobInfo | Where-Object {($_.name).split(".")[-1] -like "vhd" } | Select-Object Name,STorageaccount,LeaseStatus 27 | 28 | .EXAMPLE 29 | Get-AzureBlobInfo | Where-Object {($_.name).split(".")[-1] -like "vhd" } | Select-Object Name,STorageaccount,LeaseStatus,{($_.StorageAccountKey)[0].value} | fl 30 | 31 | List all vhd files and the storage account key, so you have all information required for removal 32 | 33 | 34 | 35 | 36 | #> 37 | [CmdletBinding()] 38 | Param( 39 | # Name of the Storage Account 40 | [Parameter(Mandatory=$false, 41 | ValueFromPipelineByPropertyName=$true, 42 | Position=0)] 43 | $StorageAccountName 44 | ) 45 | 46 | Begin{ 47 | 48 | If ($PSBoundParameters.ContainsKey("StorageAccountName")) 49 | { 50 | Write-Verbose "StorageAccount provided: $($StorageAccountName)" 51 | $storageaccounts = Get-AzureRmStorageAccount | Where-Object {$_.StorageAccountName -like "$StorageAccountName"} 52 | 53 | If ($storageaccounts -eq $null) 54 | { 55 | Write-Error "invalid Storage account: $($StorageAccountName)" 56 | } 57 | } 58 | Else 59 | { 60 | $storageaccounts = Get-AzureRmStorageAccount 61 | } 62 | } 63 | 64 | Process{ 65 | 66 | $blobinfo = @() 67 | 68 | ForEach ($sa in $storageaccounts) 69 | { 70 | 71 | $StorageKey = Get-AzureRmStorageAccountKey -ResourceGroupName $sa.ResourceGroupName -Name $sa.StorageAccountName 72 | $containers = $sa | Get-AzureStorageContainer 73 | 74 | ForEach ($cont in $containers) 75 | { 76 | $blobcontent = $cont | Get-AzureStorageBlob 77 | If ($blobcontent -eq $null) 78 | { 79 | write-verbose "Container: $($cont.name) has no blob content" 80 | } 81 | ForEach ($blob in $blobcontent) 82 | { 83 | $object = New-Object -TypeName PSObject 84 | # StorageAccount Info 85 | $object | Add-Member -MemberType NoteProperty -Name StorageAccount -Value $($sa.StorageAccountName) 86 | $object | Add-Member -MemberType NoteProperty -Name Location -Value $($sa.Location) 87 | $object | Add-Member -MemberType NoteProperty -Name SKU -Value $($sa.Sku.Name) 88 | $object | Add-Member -MemberType NoteProperty -Name StorageAccountKey -Value $StorageKey 89 | # Container Info 90 | $object | Add-Member -MemberType NoteProperty -Name ContainerName -Value $($cont.Name) 91 | $object | Add-Member -MemberType NoteProperty -Name ContainerInfo -Value $($cont) 92 | #Blob info 93 | $object | Add-Member -MemberType NoteProperty -Name BlobType -Value $($blob.BlobType) 94 | $object | Add-Member -MemberType NoteProperty -Name ICloudBlob -Value $($blob.ICloudBlob) 95 | $object | Add-Member -MemberType NoteProperty -Name Name -Value $($blob.Name) 96 | $object | Add-Member -MemberType NoteProperty -Name LeaseStatus -Value $($blob.ICloudBlob.Properties.LeaseStatus) 97 | $object | Add-Member -MemberType NoteProperty -Name LeaseState -Value $($blob.ICloudBlob.Properties.LeaseState) 98 | $object | Add-Member -MemberType NoteProperty -Name Properties -Value $($blob.ICloudBlob.Properties) 99 | $object | Add-Member -MemberType NoteProperty -Name LastModified -Value $($blob.LastModified) 100 | $blobinfo += $object 101 | } 102 | } 103 | } 104 | } 105 | 106 | End{ 107 | $blobinfo 108 | } 109 | } 110 | 111 | 112 | -------------------------------------------------------------------------------- /Azure/Utilities/Get-AzureImageSkuInfo.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | function Get-AzureImageSkuInfo 4 | { 5 | <# 6 | .Synopsis 7 | Get-AzureImageSkuInfo retrieves the available Azure Image SKUs 8 | .DESCRIPTION 9 | The Get-AzureImageSkuInfo cmdlet retrieves all image SKUs available 10 | in the offers from all publishers 11 | 12 | Use this function to identify the parameter values required for the 13 | Set-AzureRmVMSourceImage cmdlet that is used when creating new Azure VMs 14 | using New-AzureRmVM. 15 | 16 | .OUTPUT 17 | Publisher 18 | Offer 19 | SKU 20 | ID 21 | Location 22 | Version 23 | 24 | .EXAMPLE 25 | Get-AzureImageSkuInfo 26 | .EXAMPLE 27 | $allvimg = Get-AzureImageSkuInfo 28 | $allvimg | Where-Object {$_.offer -like "windows"} 29 | 30 | .NOTES 31 | Version 1.0, Alex Verboon 32 | #> 33 | [CmdletBinding()] 34 | Param() 35 | 36 | Begin{ 37 | 38 | 39 | 40 | # Use the below command to find other valid locations 41 | #Get-AzureRmResourceProvider -ListAvailable | Select-Object -ExpandProperty ResourceTypes | Select-Object -ExpandProperty Locations -Unique 42 | Try{ 43 | $Publishers =Get-AzureRmVMImagePublisher -Location "westeurope" 44 | } 45 | Catch{ 46 | # okay looks liek we're not yet connected 47 | Login-AzureRmAccount 48 | $Publishers =Get-AzureRmVMImagePublisher -Location "westeurope" 49 | } 50 | } 51 | 52 | Process{ 53 | $TotalPublishers = $Publishers.count 54 | $si=1 55 | 56 | ForEach ($pub in $Publishers) 57 | { 58 | Write-Progress -Activity "Processing $si / $TotalPublishers" -Status "Processing $($pub.PublisherName)" -PercentComplete (($si / $TotalPublishers) * 100) 59 | $offers = Get-AzureRmVMImageOffer -Location "westeurope" -PublisherName $pub.publishername -ErrorAction SilentlyContinue 60 | 61 | ForEach ($o in $offers) 62 | { 63 | write-verbose "Processing Offer: $($o.Offer)" 64 | $sku = Get-AzureRmVMImageSku -Location "westeurope" -PublisherName $pub.PublisherName -Offer $o.offer -ErrorAction SilentlyContinue 65 | 66 | ForEach ($sk in $sku) 67 | { 68 | Write-Verbose "Processing SKU: $($sk.skus)" 69 | $skuversions = Get-AzureRmVMImage -Location "westeurope" -PublisherName $sk.Publishername -Offer $sk.offer -Skus $sk.skus -ErrorAction SilentlyContinue 70 | 71 | ForEach($skuv in $skuversions) 72 | { 73 | Write-Verbose "Processing SKU version: $($skuv.version)" 74 | $props = [ordered]@{ 75 | Publisher = $sk.publishername 76 | Offer = $sk.offer 77 | SKU = $sk.skus 78 | ID = $sk.id 79 | Location = $sk.Location 80 | Version = $skuv.version 81 | } 82 | $Results += @(New-Object pscustomobject -Property $props) 83 | } 84 | } 85 | } 86 | $si++ 87 | } 88 | 89 | } 90 | 91 | End{ 92 | $Results 93 | } 94 | } 95 | 96 | 97 | -------------------------------------------------------------------------------- /Azure/Utilities/Get-AzureRmVMSizeSpecs.ps1: -------------------------------------------------------------------------------- 1 |  2 | function Get-AzureRmVMSizeSpecs 3 | { 4 | <# 5 | .Synopsis 6 | Get-AzureRmVMSizeSpecs 7 | .DESCRIPTION 8 | Get-AzureRmVMSizeSpecs 9 | .PARAMETER Location 10 | Specifies the location for which this cmdlet gets the available virtual machine sizes 11 | 12 | .PARAMETER ResourceGroupName 13 | Specifies the name of a resource group. 14 | 15 | .EXAMPLE 16 | Get-AzureRmVMSizeSpecs -Location westeurope 17 | 18 | This command gets all available virtual machine sizes in the specified location 19 | 20 | .EXAMPLE 21 | Get-AzureRmVMSizeSpecs -Location westeurope | Where-Object {$_.NumberofCores -eq 2} 22 | 23 | This command gets all available virtual machine sizes where NumberofCores is 2 24 | 25 | .EXAMPLE 26 | Get-AzureRmVMSizeSpecs -ResourceGroupName RG_2 27 | 28 | Name : VM-001 29 | HardwareProfile : Standard_D2_v2 30 | Location : westeurope 31 | NumberofCores : 2 32 | MemoryInMB : 7168 33 | MaxDataDiskCount : 4 34 | OSDiskSizeInMB : 1047552 35 | ResourceDiskSizeInMB : 102400 36 | 37 | Name : DC1 38 | HardwareProfile : Basic_A2 39 | Location : westeurope 40 | NumberofCores : 2 41 | MemoryInMB : 3584 42 | MaxDataDiskCount : 4 43 | OSDiskSizeInMB : 1047552 44 | ResourceDiskSizeInMB : 61440 45 | 46 | This command gets the VM size confirmation details for all virtual machines deployed within 47 | the specified ResourceGroup 48 | 49 | .EXAMPLE 50 | ForEach ($rg in Get-AzureRmResourceGroup) {Get-AzureRmVMSizeSpecs -ResourceGroupName $rg.ResourceGroupName -Verbose} 51 | 52 | Lists all the VM size information within each resource group that has virtual machine resources 53 | 54 | 55 | .NOTES 56 | alex verboon, version 1.0, 07/2017 57 | 58 | #> 59 | [CmdLetBinding()] 60 | Param 61 | ( 62 | # Specifies the location for which this cmdlet gets the available virtual machine sizes 63 | [Parameter(ParameterSetName = "Location", 64 | Mandatory=$true, 65 | ValueFromPipelineByPropertyName=$false, 66 | Position=0)] 67 | [validateset("australiaeast","australiasoutheast","brazilsouth","canadacentral", 68 | "canadaeast","centralus","eastasia","eastus","eastus2","japaneast","japanwest","northcentralus", 69 | "northeurope","southcentralus","southeastasia","uksouth","ukwest","westcentralus", 70 | "westeurope","westus","westus2")] 71 | $Location, 72 | 73 | # Specifies the name of a resource group. 74 | [Parameter(ParameterSetName = "ResourceGroup", 75 | Mandatory=$true, 76 | ValueFromPipelineByPropertyName=$false, 77 | Position=0)] 78 | $ResourceGroupName 79 | ) 80 | 81 | Begin 82 | { 83 | Try{ 84 | $null = Get-AzureRmSubscription 85 | } 86 | Catch{ 87 | $null = Login-AzureRmAccount 88 | } 89 | } 90 | Process 91 | { 92 | if ($PSBoundParameters.ContainsKey("Location")) 93 | { 94 | $Results = Get-AzureRmVMSize -Location $Location 95 | } 96 | 97 | if ($PSBoundParameters.ContainsKey("ResourceGroupName")) 98 | { 99 | $vminfo = Get-AzureRmVM -ResourceGroupName $ResourceGroupName 100 | If ($($vminfo).count -gt 0) 101 | { 102 | ForEach ($vmi in $vminfo) 103 | { 104 | $sizeinfo = Get-AzureRmVMSize -Location $vmi.location | where-object {$_.name -eq "$($vmi.hardwareprofile.vmsize)"} 105 | $props = [ordered]@{ 106 | "Name" = $vmi.name 107 | "HardwareProfile" = $vmi.hardwareprofile.vmsize 108 | "Location" = $vmi.location 109 | "NumberofCores" = $sizeinfo.NumberOfCores 110 | "MemoryInMB" = $sizeinfo.MemoryinMB 111 | "MaxDataDiskCount" = $sizeinfo.MaxDataDiskCount 112 | "OSDiskSizeInMB" = $sizeinfo.OSDiskSizeInMB 113 | "ResourceDiskSizeInMB" = $sizeinfo.ResourceDiskSizeInMB 114 | } 115 | $Results += @(New-Object pscustomobject -Property $props) 116 | } 117 | } 118 | Else 119 | { 120 | Write-Verbose "ResourceGroup: $ResourceGroupName does not contain virtual machine resources" 121 | } 122 | } 123 | } 124 | End 125 | { 126 | Write-Output $Results 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /Azure/Utilities/remove-azureblobobject.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | $ctx = New-AzureStorageContext -StorageAccountName rg11099 -StorageAccountKey 5DKl43OshxXet898l1tjvbk8YFYnnbRuIjyDQlziBLfiFXbpg10JdL8/twDdapOVK2F5+dNfcHWMHcDFxGD/3w== 6 | 7 | # ($b.StorageAccountKey)[0].Value 8 | Remove-AzureStorageBlob -Blob vm12201692105728.vhd -Container vhds -Context $ctx 9 | 10 | #Remove-AzureStorageContainer bootdiagnostics-vm1-e3c7d72a-cc99-4946-8be7-9fd624feed68 -Context $ctx 11 | -------------------------------------------------------------------------------- /Azure/Utilities/select-MyAzureRmSubscription.ps1: -------------------------------------------------------------------------------- 1 | function Select-MyAzureRmSubscription 2 | { 3 | <# 4 | .Synopsis 5 | Select-MyAzureRmSubscription 6 | .DESCRIPTION 7 | The Select-MyAzureRmSubscription cmdlet provides an easy way to select an Azure Subscription 8 | and sets authentication information for cmdlets that you run in the current session. 9 | The context includes tenant subscription, and environment information. 10 | 11 | .PARAMETER SubscriptionName 12 | A list of Subscriptions that the connected user has access to. 13 | The cmdlet dynamically builds a list of accessible subscriptions 14 | 15 | .EXAMPLE 16 | Select-MyAzureRmSubscription -SubscriptionName 'Visual Studio Professional with MSDN' -verbose 17 | 18 | Sets the context to the Subscription 'Visual Studio Professional with MSDN' 19 | 20 | VERBOSE: Selected SubscriptionName: Visual Studio Professional with MSDN 21 | VERBOSE: Setting Azure Context to Visual Studio Professional with MSDN 22 | 23 | Environment : AzureCloud 24 | Account : user1@outlook.com 25 | TenantId : f2108ecc-dd4a-4b24-9f58-aaaaaaaaaaaa 26 | SubscriptionId : 46327b72-b63c-48dd-b7f9-aaaaaaaaaaaa 27 | SubscriptionName : Visual Studio Professional with MSDN 28 | CurrentStorageAccount : 29 | 30 | 31 | .NOTES 32 | Connec to Azure using Login-AzureRmAccount prior using this function 33 | 34 | Version 1.0, 21.12.2016, Alex Verboon 35 | 36 | #> 37 | [CmdletBinding()] 38 | Param() 39 | DynamicParam { 40 | $attributes = new-object System.Management.Automation.ParameterAttribute 41 | $attributes.ParameterSetName = "__AllParameterSets" 42 | $attributes.Mandatory = $false 43 | $attributeCollection = new-object -Type System.Collections.ObjectModel.Collection[System.Attribute] 44 | $attributeCollection.Add($attributes) 45 | 46 | $_Values = ((Get-AzureRmSubscription | select-object SubscriptionName | Sort-object Name).SubscriptionName) 47 | 48 | If ([string]::IsNullOrEmpty($_Values)) 49 | { 50 | Write-Error "No Subscriptions found, check your connectivity to Azure" 51 | Throw 52 | } 53 | 54 | $ValidateSet = new-object System.Management.Automation.ValidateSetAttribute($_Values) 55 | $attributeCollection.Add($ValidateSet) 56 | $SubscriptionName = new-object -Type System.Management.Automation.RuntimeDefinedParameter("SubscriptionName", [string], $attributeCollection) 57 | $paramDictionary = new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary 58 | $paramDictionary.Add("SubscriptionName", $SubscriptionName) 59 | 60 | return $paramDictionary } 61 | 62 | Begin{ 63 | $SubscriptionName = $SubscriptionName.Value 64 | Write-Verbose "Selected SubscriptionName: $SubscriptionName" 65 | } 66 | Process{ 67 | Write-verbose "Setting Azure Context to $SubscriptionName" 68 | Select-AzureRmSubscription -SubscriptionName "$SubscriptionName" 69 | } 70 | End{} 71 | } 72 | -------------------------------------------------------------------------------- /Azure/Utilities/wip/AzureFileShare.ps1: -------------------------------------------------------------------------------- 1 |  2 | # Azure File Share Stuff 3 | 4 | #http://blogs.msdn.com/b/windowsazurestorage/archive/2014/05/12/introducing-microsoft-azure-file-service.aspx 5 | 6 | 7 | $ResourceGroupName = "RG_2" 8 | $StorageAccountName = "sazureverboon01" 9 | $AccessKey = (Get-AzureRmStorageAccountKey -Name $StorageAccountName -ResourceGroupName $ResourceGroupName).Key1 10 | 11 | # create a context for account and key 12 | $ctx=New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $AccessKey 13 | 14 | 15 | # create a new share 16 | $s = New-AzureStorageShare myscripts -Context $ctx 17 | 18 | # create a directory in the test share just created 19 | New-AzureStorageDirectory -Share $s -Path testdir 20 | 21 | # upload a local file to the testdir directory just created 22 | Set-AzureStorageFileContent -Share $s -Source C:\Data\dev\posh\LICENSE -Path testdir 23 | 24 | # list out the files and subdirectories in a directory 25 | Get-AzureStorageFile -Share $s -Path testdir 26 | 27 | # download files from azure storage file service 28 | Get-AzureStorageFileContent -Share $s -Path testdir/license -Destination c:\temp 29 | 30 | # remove files from azure storage file service 31 | Remove-AzureStorageFile -Share $s -Path testdir/license 32 | 33 | 34 | 35 | $file1 = "https://sazureverboon01.file.core.windows.net/vmscripts/runme1.ps1" 36 | $vmid = ( Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name vm00111).Id 37 | 38 | Set-AzureRmVMCustomScriptExtension -Name "RunMe" -FileUri $file1 -VMName vm00111 -Run "runme1.ps1" -ResourceGroupName $ResourceGroupName -Location "westeurope" 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Azure/Utilities/wip/AzureRmResourceGroupDeployment.ps1: -------------------------------------------------------------------------------- 1 |  2 | $ResourceGroup = "RG_3" 3 | $Running = Get-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroup | Where-Object {$_.ProvisioningState -inotlike "Succeeded"} 4 | 5 | #$sel = $Running | Select-Object DeploymentName | Out-GridView -OutputMode Single 6 | #$sel.DeploymentName 7 | 8 | 9 | $operations = Get-AzureRmResourceGroupDeploymentOperation –DeploymentName $Deploymentname –ResourceGroupName $ResourceGroup 10 | 11 | foreach($operation in $operations) 12 | 13 | { 14 | Write-Host $operation.id 15 | Write-Host "Request:" 16 | $operation.Properties.Request | ConvertTo-Json -Depth 10 17 | Write-Host "Response:" 18 | $operation.Properties.Response | ConvertTo-Json -Depth 10 19 | } 20 | 21 | -------------------------------------------------------------------------------- /Azure/Utilities/wip/ConfigureWinRM_HTTPS.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | # Ensure PS remoting is enabled, although this is enabled by default for Azure VMs 4 | Enable-PSRemoting -Force 5 |   6 | # Create rule in Windows Firewall 7 | New-NetFirewallRule -Name "WinRM HTTPS" -DisplayName "WinRM HTTPS" -Enabled True -Profile Any -Action Allow -Direction Inbound -LocalPort 5986 -Protocol TCP 8 |   9 | # Create Self Signed certificate and store thumbprint 10 | $thumbprint = (New-SelfSignedCertificate -DnsName $env:COMPUTERNAME -CertStoreLocation Cert:\LocalMachine\My).Thumbprint 11 |   12 | # Run WinRM configuration on command line. DNS name set to computer hostname, you may wish to use a FQDN 13 | $cmd = "winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname=""$env:computername""; CertificateThumbprint=""$thumbprint""}" 14 | cmd.exe /C $cmd -------------------------------------------------------------------------------- /Azure/Utilities/wip/Scriptsfolder.ps1: -------------------------------------------------------------------------------- 1 | #http://www.techdiction.com/2016/02/12/create-a-custom-script-extension-for-an-azure-resource-manager-vm-using-powershell/ 2 | 3 | $rgname = "rg_vm" 4 | $VMName = "vm4" 5 | $file = "C:\Data\dev\posh\Azure\Utilities\ConfigureWinRM_HTTPS.ps1" 6 | $containerName = "script-container" 7 | 8 | # Get the VM we need to configure 9 | $vm = Get-AzureRmVM -ResourceGroupName $rgname -Name $VMName 10 | 11 | # Get storage account name 12 | $storageaccountname = $vm.StorageProfile.OsDisk.Vhd.Uri.Split('.')[0].Replace('https://','') 13 | 14 | # get storage account key 15 | $key = (Get-AzureRmStorageAccountKey -Name $storageaccountname -ResourceGroupName $rgname).Key1 16 | 17 | # create storage context 18 | $storagecontext = New-AzureStorageContext -StorageAccountName $storageaccountname -StorageAccountKey $key 19 | 20 | # create a container called scripts 21 | New-AzureStorageContainer -Name "scripts" -Context $storagecontext 22 | 23 | #upload the file 24 | Set-AzureStorageBlobContent -Container "scripts" -File "$file" -Context $storagecontext -Blob "ConfigureWinRM_HTTPS.ps1" -BlobType Page 25 | 26 | 27 | 28 | 29 | # Create custom script extension from uploaded file 30 | #Set-AzureRmVMCustomScriptExtension -ResourceGroupName $rgname -VMName $vmname -Name "EnableWinRM_HTTPS" -Location $vm.Location -StorageAccountName $storageaccountname -StorageAccountKey $key -FileName "ConfigureWinRM_HTTPS.ps1" -ContainerName "scripts" 31 | -------------------------------------------------------------------------------- /Azure/Utilities/wip/Untitled1.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | if (!$AzureRMAccount.Context.Tenant) { 4 | $AzureRMAccount = Add-AzureRmAccount 5 | } 6 | -------------------------------------------------------------------------------- /BlockChain/samples.txt: -------------------------------------------------------------------------------- 1 | 0x627306090abab3a6e1400e9345bc60c78a8bef57 2 | 0xf17f52151ebef6c7334fad080c5704d77216b732 3 | 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef 4 | 5 | MetaCoin.getBalance('0x627306090abab3a6e1400e9345bc60c78a8bef57') 6 | MetaCoin.getBalance('0xf17f52151ebef6c7334fad080c5704d77216b732') 7 | MetaCoin.getBalance('0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef') 8 | 9 | web3.eth.getBalance('0x627306090abab3a6e1400e9345bc60c78a8bef57') 10 | web3.eth.getBalance('0xf17f52151ebef6c7334fad080c5704d77216b732') 11 | web3.eth.getBalance('0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef') 12 | 13 | MetaCoin.sendCoin('0xf17f52151ebef6c7334fad080c5704d77216b732', 123, {from: '0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef'}); 14 | 15 | web3.eth.sendTransaction({from: '0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef', to: '0xf17f52151ebef6c7334fad080c5704d77216b732', value: web3.toWei(5, 'ether'), gasLimit: 21000, gasPrice: 20000000000}) 16 | 17 | 18 | // get accounts 19 | 20 | web3.eth.accounts 21 | 22 | // get reference to deployed contract 23 | 24 | var MetaCoin; 25 | MetaCoin.deployed().then(function(deployed) {MetaCoin = deployed;}); 26 | 27 | // get balance of account 0 28 | MetaCoin.getBalance.call(web3.eth.accounts[0]) 29 | 30 | // send coins 31 | var account0 = web3.eth.accounts[0]; 32 | var account1 = web3.eth.accounts[1]; 33 | MetaCoin.sendCoin(account1, 1000, {from: account0}); 34 | 35 | https://github.com/trufflesuite/truffle-contract 36 | https://dzone.com/articles/ethereum-hello-world-example-using-solc-and-web3 37 | 38 | npm install solc 39 | 40 | 41 | https://ethereum.stackexchange.com/questions/17983/compiling-solidity-code-using-solc0-4-10-on-node-js 42 | 43 | 44 | const fs = require("fs"); 45 | abiDecoder = require('abi-decoder'); 46 | Web3 = require('web3'); 47 | solc = require('solc'); 48 | 49 | 50 | var input = { 51 | 'ConvertLib.sol': fs.readFileSync('contracts/ConvertLib.sol', 'utf8'), 52 | 'MetaCoin.sol': fs.readFileSync('contracts/MetaCoin.sol', 'utf8'), 53 | }; 54 | 55 | 56 | 57 | let compiledContract = solc.compile({sources: input}, 1); 58 | let abi = compiledContract.contracts['MetaCoin.sol:MetaCoin'].interface; 59 | let bytecode = '0x'+compiledContract.contracts['MetaCoin.sol:MetaCoin'].bytecode; 60 | 61 | let abi2 = JSON.parse(compiledContract.contracts['MetaCoin.sol:MetaCoin'].interface); 62 | abiDecoder.addABI(abi2); 63 | 64 | web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545")); 65 | 66 | let gasEstimate = web3.eth.estimateGas({data: bytecode}); 67 | let MetaC = web3.eth.contract(JSON.parse(abi)); 68 | 69 | finale = web3.eth.getTransaction('0xc8cbab4d6af3d241d160d888c061e6fa4cda56b83454cfe17a2449c345f14aca') 70 | abiDecoder.decodeMethod(finale.input); 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /BlockChain/stuff.txt: -------------------------------------------------------------------------------- 1 | 0x627306090abab3a6e1400e9345bc60c78a8bef57 2 | 0xf17f52151ebef6c7334fad080c5704d77216b732 3 | 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef 4 | 5 | MetaCoin.getBalance('0x627306090abab3a6e1400e9345bc60c78a8bef57') 6 | MetaCoin.getBalance('0xf17f52151ebef6c7334fad080c5704d77216b732') 7 | MetaCoin.getBalance('0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef') 8 | 9 | web3.eth.getBalance('0x627306090abab3a6e1400e9345bc60c78a8bef57') 10 | web3.eth.getBalance('0xf17f52151ebef6c7334fad080c5704d77216b732') 11 | web3.eth.getBalance('0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef') 12 | 13 | MetaCoin.sendCoin('0xf17f52151ebef6c7334fad080c5704d77216b732', 123, {from: '0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef'}); 14 | 15 | web3.eth.sendTransaction({from: '0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef', to: '0xf17f52151ebef6c7334fad080c5704d77216b732', value: web3.toWei(5, 'ether'), gasLimit: 21000, gasPrice: 20000000000}) 16 | 17 | 18 | // get accounts 19 | 20 | web3.eth.accounts 21 | 22 | // get reference to deployed contract 23 | 24 | var MetaCoin; 25 | MetaCoin.deployed().then(function(deployed) {MetaCoin = deployed;}); 26 | 27 | // get balance of account 0 28 | MetaCoin.getBalance.call(web3.eth.accounts[0]) 29 | 30 | // send coins 31 | var account0 = web3.eth.accounts[0]; 32 | var account1 = web3.eth.accounts[1]; 33 | MetaCoin.sendCoin(account1, 1000, {from: account0}); 34 | 35 | https://github.com/trufflesuite/truffle-contract 36 | https://dzone.com/articles/ethereum-hello-world-example-using-solc-and-web3 37 | 38 | npm install solc 39 | 40 | 41 | https://ethereum.stackexchange.com/questions/17983/compiling-solidity-code-using-solc0-4-10-on-node-js 42 | 43 | 44 | const fs = require("fs"); 45 | abiDecoder = require('abi-decoder'); 46 | Web3 = require('web3'); 47 | solc = require('solc'); 48 | 49 | 50 | var input = { 51 | 'ConvertLib.sol': fs.readFileSync('contracts/ConvertLib.sol', 'utf8'), 52 | 'MetaCoin.sol': fs.readFileSync('contracts/MetaCoin.sol', 'utf8'), 53 | }; 54 | 55 | 56 | 57 | let compiledContract = solc.compile({sources: input}, 1); 58 | let abi = compiledContract.contracts['MetaCoin.sol:MetaCoin'].interface; 59 | let bytecode = '0x'+compiledContract.contracts['MetaCoin.sol:MetaCoin'].bytecode; 60 | 61 | let abi2 = JSON.parse(compiledContract.contracts['MetaCoin.sol:MetaCoin'].interface); 62 | abiDecoder.addABI(abi2); 63 | 64 | web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545")); 65 | 66 | let gasEstimate = web3.eth.estimateGas({data: bytecode}); 67 | let MetaC = web3.eth.contract(JSON.parse(abi)); 68 | 69 | finale = web3.eth.getTransaction('0xc8cbab4d6af3d241d160d888c061e6fa4cda56b83454cfe17a2449c345f14aca') 70 | abiDecoder.decodeMethod(finale.input); 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /CIS/Get-CISBenchMarkProfiles.ps1: -------------------------------------------------------------------------------- 1 | Function Get-CISBenchMarkProfiles { 2 | <# 3 | .SYNOPSIS 4 | Get-CISBenchMarkProfiles 5 | .DESCRIPTION 6 | Get-CISBenchMarkProfiles list the available Profiles that are available for the 7 | selected CIS Benchmark. 8 | .PARAMETER CISCATPath 9 | The Path where CIS-CAT is installed 10 | .PARAMETER BenchMark 11 | The name of the Benchmark. List is automatically populated based on content within 12 | the CIS-CAT Benchmark folder. 13 | 14 | Use this script to identify the available profiles when updating, extending the INvoke=CISCAT cmdlet code. 15 | 16 | .EXAMPLE 17 | Get-CISBenchMarkProfiles -CISCATPath C:\temp\CISTEMP -Benchmark CIS_Microsoft_Windows_10_Enterprise_Release_1703_Benchmark_v1.3.0-xccdf.xml 18 | 19 | The above command lists all profiles that are availble for the selected CIS Benchmark. 20 | 21 | xccdf_org.cisecurity.benchmarks_profile_Level_1 22 | xccdf_org.cisecurity.benchmarks_profile_Level_1__BitLocker 23 | xccdf_org.cisecurity.benchmarks_profile_Level_2 24 | xccdf_org.cisecurity.benchmarks_profile_Level_2__BitLocker 25 | 26 | .NOTES 27 | version 1.0, 23.01.2014, alex verboon 28 | .LINK 29 | https://oval.cisecurity.org/ 30 | #> 31 | [CmdletBinding()] 32 | Param( 33 | [Parameter(Mandatory=$true,Position=2)] 34 | [ValidateScript( 35 | { 36 | if ((Test-Path "$_\cis-cat-full\CISCAT.jar")) 37 | { 38 | write-verbose "$_\cis-cat-full\CISCAT.jar found" 39 | $true 40 | } 41 | else 42 | { 43 | Throw "Unable to find $_\cis-cat-full\CISCAT.jar." 44 | }})] 45 | [string]$CISCATPath 46 | ) 47 | 48 | DynamicParam { 49 | 50 | # Set the dynamic parameters' name 51 | $ParameterName = 'Benchmark' 52 | 53 | # Create the dictionary 54 | $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary 55 | 56 | # Create the collection of attributes 57 | $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] 58 | 59 | # Create and set the parameters' attributes 60 | $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute 61 | $ParameterAttribute.Mandatory = $true 62 | $ParameterAttribute.Position = 3 63 | 64 | # Add the attributes to the attributes collection 65 | $AttributeCollection.Add($ParameterAttribute) 66 | 67 | # Generate and set the ValidateSet 68 | $arrSet = Get-ChildItem -Path "$CISCATPath\CIS-CAT-FULL\Benchmarks" -Filter "*.xml" 69 | $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) 70 | 71 | # Add the ValidateSet to the attributes collection 72 | $AttributeCollection.Add($ValidateSetAttribute) 73 | 74 | # Create and return the dynamic parameter 75 | $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) 76 | $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) 77 | return $RuntimeParameterDictionary 78 | } 79 | 80 | 81 | Begin { 82 | 83 | } 84 | 85 | Process{ 86 | $BenchMarkFile = "$CISCATPath\CIS-CAT-FULL\Benchmarks\$($PSBoundParameters["BenchMark"])" 87 | Try{ 88 | [xml]$BenchmarkContent = Get-Content -Path $BenchMarkFile 89 | } 90 | Catch{ 91 | Write-error $_.Exception.Message 92 | } 93 | } 94 | 95 | End{ 96 | Write-Verbose "Available Profiles in Brenchmark: $($PSBoundParameters["BenchMark"])" 97 | $BenchmarkContent.Benchmark.Profile | Select-Object -ExpandProperty ID 98 | } 99 | } -------------------------------------------------------------------------------- /CIS/Install-CISCATToolkit.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Install-CISCATToolkit{ 3 | <# 4 | .SYNOPSIS 5 | Install-CISCATToolkit 6 | .DESCRIPTION 7 | Install-CISCATToolkit Downloads and installs the CIS Configuration Assessment Toolkit" 8 | .PARAMETER Path 9 | The Path where CIS-CAT will be installed 10 | .EXAMPLE 11 | Install-CISCATToolkit -Path C:\TEMP\CISCAT 12 | .NOTES 13 | version 1.0, 23.01.2018, alex verboon 14 | #> 15 | 16 | [CmdletBinding()] 17 | Param( 18 | [Parameter(Mandatory=$true,Position=1)] 19 | [string]$Path 20 | ) 21 | 22 | Begin{ 23 | 24 | # Create the CIS-CAT Toolkit Folder 25 | If (Test-Path -Path $Path -PathType Container) 26 | { 27 | Write-Warning "Folder $Path already exists, please specify another folder or delete this folder first" 28 | Throw 29 | } 30 | Else 31 | { 32 | New-Item -Path "$Path" -ItemType Directory | Out-Null 33 | } 34 | 35 | 36 | } 37 | 38 | Process{ 39 | Try{ 40 | # Pointer to latest CIS-CAT Toolit Bundle, adjust location 41 | $CISBundleZip = "https://" 42 | Write-Output "Locating CIS-CAT Toolkit source: $CISBundleZip" 43 | 44 | # Check if file exists 45 | $CheckIt = Invoke-WebRequest $CISBundleZip -Method Head 46 | If (-not ($CheckIt.StatusCode -eq 200)) 47 | { 48 | Throw ("Unable to find $CISBundleZip") 49 | } 50 | Else 51 | { 52 | # Download the CIS-CAT Toolkit Archive 53 | Write-Output "Downloading CIS-CAT Toolkit Archive" 54 | Invoke-WebRequest -Uri $CISBundleZip -Method get -OutFile "$Path\cis-cat-dissolvable.zip" -UseDefaultCredentials 55 | 56 | # Extract the CIS-CAT ToolKit Archive 57 | Write-Output "Extracting $Path\cis-cat-dissolvable.zip to $Path" 58 | Expand-Archive -Path "$Path\cis-cat-dissolvable.zip" -DestinationPath "$Path" 59 | 60 | # Verify correct expansion, we just check for the existence of a particular CIS-CAT file. 61 | Write-Output "Verifying installtaion" 62 | If (Test-Path "$Path\cis-cat-full\CISCAT.jar" -PathType Leaf) 63 | { 64 | Write-Output "CIS-CAT Toolkit successfully installed in $Path" 65 | } 66 | Else 67 | { 68 | Throw ("$Path\cis-cat-full\CISCAT.jar could not be found") 69 | } 70 | } 71 | } 72 | Catch{ 73 | Write-Warning "Something went wrong while downloading and installing CIS-CAT Toolkit" 74 | Write-error $_.Exception.Message 75 | } 76 | } 77 | 78 | End{ 79 | Write-Output " 80 | 81 | You can now continue using the CIS-CAT Toolkit. 82 | 83 | Use Update-CISVulnDefinitions to update the Vulnerability Assessment definitions 84 | 85 | Use Invoke-CISCAT to start a Configuration Baseline or Vulnerability Assessment" 86 | } 87 | } 88 | 89 | 90 | -------------------------------------------------------------------------------- /CIS/Update-CISVulnDefinitions.ps1: -------------------------------------------------------------------------------- 1 | Function Update-CISVulnDefinitions { 2 | <# 3 | .SYNOPSIS 4 | Update-CISVulnDefinitions 5 | .DESCRIPTION 6 | Update-CISVulnDefinitions 7 | .PARAMETER Path 8 | The location where Windows Vulnerability definitions are stored locally. 9 | .EXAMPLE 10 | Update-CISVulnDefinitions -Path C:\TEMP\CISCAT 11 | .NOTES 12 | 13 | .LINK 14 | https://oval.cisecurity.org/ 15 | #> 16 | [CmdletBinding()] 17 | Param ( 18 | [Parameter(Mandatory=$true,Position=1)] 19 | [string]$Path) 20 | Begin { 21 | 22 | #https://www.ssllabs.com/ssltest/analyze.html?d=www.verboon.info&latest 23 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 24 | 25 | $WinVulnDefUri = "https://oval.cisecurity.org/repository/download/5.10/vulnerability/" 26 | $CIS_VulnDef_Dir="cis-cat-full\third-party-content\org.mitre.oval" 27 | $RandomName = (([GUID]::NewGuid()).guid) 28 | 29 | If ((Test-Path "$Path\$CIS_VulnDef_Dir" -PathType Container) -eq $false) 30 | { 31 | Write-Verbose "$Path\$CIS_VulnDef_Dir does not exist, creating it now" 32 | New-Item -Path "$Path\$CIS_VulnDef_Dir" -ItemType Container | Out-Null 33 | } 34 | } 35 | 36 | Process { 37 | $WinVulnDefUriContent = Invoke-WebRequest -Uri $WinVulnDefUri 38 | $Downloadlinks = ($WinVulnDefUriContent.Links | Select-Object href | Where-Object {$_.href -like "*Microsoft_windows_10.xml" -or $_.href -like "*Microsoft_Windows_7.xml"}).href 39 | 40 | ForEach($osuri in $downloadlinks) 41 | { 42 | $downloadfilename = Split-Path $osuri -Leaf 43 | Write-Verbose "Downloading Source: $downloadfilename" 44 | Write-Verbose "Target: $Path\$CIS_VulnDef_Dir\$RandomName`_$downloadfilename" 45 | $dltask = Invoke-WebRequest -Uri $osuri -Method Get -OutFile "$Path\$CIS_VulnDef_Dir\$RandomName`_$downloadfilename" 46 | } 47 | 48 | # Gather the downloaded files 49 | $DownloadedFiles = Get-ChildItem -Path "$Path\$CIS_VulnDef_Dir" -Filter "$RandomName*.xml" 50 | # The OVAL XML file must contain the following XML nodes 51 | $oval_requirednodes = @( 52 | "generator", 53 | "definitions", 54 | "tests", 55 | "objects", 56 | "states", 57 | "variables") 58 | 59 | $Result = @() 60 | ForEach ($checkfile in $DownloadedFiles) 61 | { 62 | Write-Verbose "File: $($checkfile.FullName)" 63 | [xml]$vuldeffile = Get-Content -Path "$($checkfile.FullName)" 64 | $xmlnodes = ($vuldeffile.oval_definitions.ChildNodes | Select Name).Name 65 | $checkovalschema = Compare-Object -ReferenceObject $oval_requirednodes -DifferenceObject $xmlnodes 66 | If ($check -ne $null ) 67 | { 68 | Write-Warning "XML file does not seem to have the right nodes" 69 | } 70 | Else 71 | { 72 | $NewFileName = $checkfile.FullName -replace "$RandomName`_","" 73 | Write-Verbose "New FileName: $NewFileName" 74 | If (Test-Path $NewFileName) 75 | { 76 | Remove-Item -Path $NewFileName -Force 77 | } 78 | Rename-Item -Path $checkfile.FullName -NewName $NewFileName 79 | $Result = $Result + $NewFileName 80 | } 81 | } 82 | } 83 | 84 | End { 85 | $Result 86 | } 87 | } 88 | 89 | -------------------------------------------------------------------------------- /ConfigMgr/get-cmclientpolicysettings.ps1: -------------------------------------------------------------------------------- 1 | Function Get-CMclientpolicysettings 2 | { 3 | <# 4 | .Synopsis 5 | Get-CMclientpolicysettings 6 | .DESCRIPTION 7 | Get-CMclientpolicysettings retrieves Configuration Manager client agent policy settings. 8 | .PARAMETER Name 9 | The ConfigMgr Agent Policy Name 10 | .EXAMPLE 11 | Get-CMclientpolicysettings 12 | .EXAMPLE 13 | Get-CMclientpolicysettings -Name "Workstation Settings" 14 | .NOTES 15 | version 1.1, 21.02.2017, Alex Verboon 16 | #> 17 | 18 | [CmdletBinding()] 19 | Param( 20 | 21 | # ConfigMgr Agent Policy Name 22 | [Parameter(Mandatory=$false, 23 | ValueFromPipelineByPropertyName=$true, 24 | Position=0)] 25 | $Name 26 | ) 27 | 28 | Begin{ 29 | 30 | Write-verbose "Retrieving Policies" 31 | if ($PSBoundParameters.ContainsKey("Name")) 32 | { 33 | $cmpolicies = Get-CMClientSetting | Select-Object Name | Where-Object {$_.Name -eq "$Name"} 34 | } 35 | Else 36 | { 37 | $cmpolicies = Get-CMClientSetting | Select-Object Name 38 | } 39 | } 40 | 41 | 42 | Process{ 43 | $Results = @() 44 | foreach ($policy in $cmpolicies ) 45 | { 46 | write-verbose "$($Policy.name)" 47 | $xsettings = [Enum]::GetNames( [Microsoft.ConfigurationManagement.Cmdlets.ClientSettings.Commands.SettingType]) 48 | foreach ($setting in $xsettings) 49 | { 50 | Write-verbose $setting 51 | $configuration = Get-CMClientSetting -Setting $setting -Name $Pol.name 52 | ForEach ($config in $configuration.GetEnumerator()) 53 | { 54 | write-verbose $config.Key 55 | $data = [ordered] @{ 56 | PolicyName = $policy.Name 57 | Setting = $setting 58 | ConfigurationName = $config.Key 59 | ConfigurationValue = $config.Value 60 | } 61 | $Results += (New-Object -TypeName psobject -Property $data) 62 | } 63 | } 64 | } 65 | } 66 | 67 | End{Write-Output $Results} 68 | 69 | } -------------------------------------------------------------------------------- /ConfigMgr/reame.md: -------------------------------------------------------------------------------- 1 | # ConfigMgr utilities 2 | 3 | ## Get-CMClientPolicySettings 4 | This function retrieves the Client Policy settings configured within ConfigMgr. 5 | -------------------------------------------------------------------------------- /ELK/MyElkPoShSnippets.ps1: -------------------------------------------------------------------------------- 1 | # A few PowerShell snippets and notes I put together while playing with ELK 2 | 3 | 4 | Function Get-ELKIndexPattern 5 | { 6 | $indp = Invoke-WebRequest -Uri http://localhost:9200/_cat/indices?v 7 | $indp.Content 8 | 9 | } 10 | 11 | Function Delete-ELKWinlogbeatdocs 12 | { 13 | Write-Warning "This will delete all previously uploaded log data to WinLogBeat" 14 | PAUSE 15 | Invoke-WebRequest -Uri 'http://localhost:9200/winlogbeat-*' -Method Delete 16 | } 17 | 18 | # loading index template 19 | #https://www.elastic.co/guide/en/beats/winlogbeat/current/winlogbeat-template.html 20 | # nvoke-WebRequest -Method Put -InFile "C:\Data\winlogbeat-5.2.2-windows-x86_64\winlogbeat.template.json" -Uri http://localhost:9200/_template/winlogbeat?pretty 21 | 22 | 23 | 24 | Function Install-WinLogBeatService{ 25 | 26 | # delete service if it already exists 27 | if (Get-Service winlogbeat -ErrorAction SilentlyContinue) { 28 | $service = Get-WmiObject -Class Win32_Service -Filter "name='winlogbeat'" 29 | $service.StopService() 30 | Start-Sleep -s 1 31 | $service.delete() 32 | } 33 | $workdir = Split-Path $MyInvocation.MyCommand.Path 34 | 35 | # create new service 36 | New-Service -name winlogbeat ` 37 | -displayName winlogbeat ` 38 | -binaryPathName "`"$workdir\\winlogbeat.exe`" -c `"$workdir\\winlogbeat.yml`" -path.home `"$workdir`" -path.data `"C:\\ProgramData\\winlogbeat`"" 39 | } 40 | 41 | 42 | 43 | <# Web Resources 44 | 45 | http://robwillis.info/2016/05/installing-elasticsearch-logstash-and-kibana-elk-on-windows-server-2012-r2/ 46 | 47 | 48 | 49 | #> 50 | 51 | I -------------------------------------------------------------------------------- /GroupPolicy/Get-GpoExtensionInfo.ps1: -------------------------------------------------------------------------------- 1 | Function Get-GpoExtensionInfo{ 2 | <# 3 | .SYNOPSIS 4 | Get-GpoExtensionInfo 5 | .DESCRIPTION 6 | Get-GpoExtensionInfo retrieves the following Group Policy Extension 7 | information from the local computer. 8 | 9 | Name, Description, GUID 10 | 11 | .EXAMPLE 12 | Get-GpoExtensionInfo 13 | 14 | The above command retrieves Group Policy Extension information. 15 | 16 | .NOTES 17 | v1, 23.02.2018, alex verboon 18 | #> 19 | 20 | 21 | Begin{ 22 | Try{ 23 | $GpoReportingDll = (Get-ChildItem -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.GroupPolicy.Reporting\*.dll" -Recurse).fullname 24 | Add-Type -Path "$GpoReportingDll" 25 | } 26 | Catch{ 27 | Write-Error "Unable to load Microsoft.GroupPolicy.Reporting.dll" 28 | Throw 29 | } 30 | } 31 | 32 | Process{ 33 | $GpoExtensionInfo = @() 34 | $GpoExtensionNames = ([Microsoft.GroupPolicy.Reporting.ExtensionNames].GetFields()).Name 35 | ForEach ($ExtN in $GpoExtensionNames) 36 | { 37 | $ExtName = [Microsoft.GroupPolicy.Reporting.ExtensionNames]::$ExtN 38 | $ExtGUID = [Microsoft.GroupPolicy.Reporting.ExtensionIDs]::$ExtN 39 | 40 | $object = [ordered]@{ 41 | Name = $ExtN 42 | Description = $ExtName 43 | GUID = $ExtGUID 44 | } 45 | $GpoExtensionInfo += (New-Object -TypeName psobject -Property $object) 46 | } 47 | } 48 | 49 | End{ 50 | $GpoExtensionInfo 51 | } 52 | } 53 | 54 | 55 | -------------------------------------------------------------------------------- /GroupPolicy/install-GroupPolicyXtended.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Installs the GroupPolicyXtended PowerShell Module 4 | 5 | .DESCRIPTION 6 | This script triggers the installation of the GroupPolicyXtended PowerShell 7 | Module. The module is installed in 8 | C:\Users\\WindowsPowerShell\Modules\GroupPolicyXtended 9 | 10 | .NOTES 11 | Credits for this module installer script goes to my friend Claude Henchoz 12 | 13 | Version 1.0 14 | #> 15 | 16 | 17 | # URL to .psm1 file 18 | $Url = "https://raw.githubusercontent.com/alexverboon/posh/master/GroupPolicy/GroupPolicyXtended.psm1" 19 | 20 | function Install-ModuleFromUri { 21 | Param([Parameter(Mandatory=$true,Position=0)][string]$Uri) 22 | 23 | # File name of URL without extension 24 | $modname = (([System.Uri]"$Uri".Replace("?raw","")).Segments[-1]).Split(".")[0] 25 | 26 | # Create local module path 27 | $modpath = [environment]::getfolderpath("mydocuments") + ` 28 | "\WindowsPowerShell\Modules\$modname" 29 | 30 | # Create module folder(s) if it doesn't exist 31 | if (!(Test-Path $modpath)) { 32 | New-Item -itemtype "Directory" $modpath -force | Out-Null 33 | } 34 | 35 | # Download module 36 | Invoke-WebRequest $Uri -OutFile "$modpath\$modname.psm1" -UseDefaultCredential 37 | 38 | # Import so it becomes immediately loaded 39 | Import-Module "$modpath\$modname.psm1" -Force 40 | 41 | Write-Output "Done installing $modname!`n" 42 | Write-Output "Installed from: $Uri" 43 | Write-Output "Installed to: $modpath`n" 44 | Write-Output "Run `"gcm -m $modname`" to get a list of features." 45 | } 46 | 47 | Install-ModuleFromUri -Uri "$Url" 48 | -------------------------------------------------------------------------------- /GroupPolicy/readme.md: -------------------------------------------------------------------------------- 1 | # The GroupPolicyXtended Module 2 | 3 | This module contains cmdlets for Group Policy management 4 | 5 | ## Installation 6 | In order to install the module, open a PowerShell prompt and paste the following line (triple-click to select all of it), then press [ENTER]. 7 | 8 | `$wc=New-Object System.Net.WebClient;$wc.UseDefaultCredentials=$true;iex $wc.DownloadString("https://raw.githubusercontent.com/alexverboon/posh/master/GroupPolicy/install-GroupPolicyXtended.ps1")` 9 | 10 | The module is installed into C:\Users\\Documents\WindowsPowerShell\Modules\GroupPolicyXtended 11 | 12 | 13 | ## Update 14 | Run Update-GroupPolicyXtended to update the module to the latest version 15 | 16 | ## Topics 17 | 18 | ### Get-GPEventByCorrelationID 19 | This function retrieves Group Policy event log entries filtered by Correlation ID from the specified computer 20 | 21 | ###Get-GPProcessingtime 22 | The Get-GPProcessingtime cmdlet gets Group Policy processing time for the user and computer related 23 | Group Policies that are processed on the specified computer(s). 24 | 25 | ###Set-GPLogging 26 | The Set-GPLogging cmdlet enables or disables Group Policy Service or Group Policy Preferences 27 | logging. 28 | 29 | ###Get-GPLogging 30 | The Get-GPLogging cmdlet retrieves information about the Group Policy Service Debug 31 | or Group Policy Preference logging configuration set on a computer. 32 | 33 | ###Update-GroupPolicyXtended 34 | Run this cmdlet to update the module to the latest version. 35 | 36 | 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 alexverboon 4 | 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /Office365/LicenseManagement/Get-msoluserlicensestatus.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Get-msoluserlicensestatus 4 | .DESCRIPTION 5 | Get-msoluserlicensestatus lists all Office 365 Serviceplans,license options 6 | and provisioning status of these for the specified user 7 | status 8 | .PARAMETER UserPrincipalName 9 | The user ID of the user to retrieve. 10 | .EXAMPLE 11 | Get-msoluserlicensestatus -UserPrincipalName alex@foocorp.com 12 | 13 | AccountSkuID ServicePlan ServiceType Provisioning 14 | Status 15 | ------------ ----------- ----------- ------------ 16 | 17 | foocorp:ENTERPRISEWITHSCAL MCOSTANDARD MicrosoftCommunicationsOnline Success 18 | foocorp:ENTERPRISEWITHSCAL SHAREPOINTWAC SharePoint Success 19 | foocorp:ENTERPRISEWITHSCAL SHAREPOINTENTERPRISE SharePoint Success 20 | .... 21 | 22 | 23 | .PARAMETER UserPrincipalName 24 | The user ID of the user to retrieve. 25 | .NOTES 26 | Version 1.0, 18.11.2016, Alex Verboon 27 | #> 28 | function Get-msoluserlicensestatus 29 | { 30 | [CmdletBinding()] 31 | Param 32 | ( 33 | # The user ID of the user to retrieve. 34 | [Parameter(Mandatory=$true, 35 | ValueFromPipelineByPropertyName=$true, 36 | Position=0)] 37 | $UserPrincipalName 38 | ) 39 | 40 | Begin 41 | { 42 | 43 | Try 44 | { 45 | Get-MsolDomain -ErrorAction Stop > $null 46 | 47 | } 48 | catch 49 | { 50 | write-error "You must call the Connect-MsolService cmdlet before calling any other cmdlets" 51 | Throw 52 | } 53 | 54 | $userinfo = Get-MsolUser -UserPrincipalName $UserPrincipalName 55 | 56 | } 57 | Process 58 | { 59 | 60 | $licinfo = $userinfo | Select-Object -ExpandProperty licenses 61 | $output = @() 62 | 63 | ForEach ($i in $licinfo) 64 | { 65 | $serviceplan = $i | Select-Object -ExpandProperty ServiceStatus 66 | ForEach($sp in $serviceplan) 67 | { 68 | $o = [PSCustomObject]@{ 69 | AccountSkuID = $i.AccountSkuId 70 | #SkuID = ($i.AccountSkuId -split (":"))[1] 71 | ServicePlan = $sp.ServicePlan.ServiceName 72 | ServiceType = $sp.ServicePlan.ServiceType 73 | ProvisioningStatus = $sp.ProvisioningStatus 74 | #TargetClass = $sp.ServicePlan.TargetClass 75 | #ServicePlanID = $sp.ServicePlan.ServicePlanId 76 | } 77 | $output += $o 78 | } 79 | } 80 | } 81 | End 82 | { 83 | $output 84 | } 85 | } 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /Office365/Monitoring/Get-ServiceHealthDashboard.ps1: -------------------------------------------------------------------------------- 1 |  2 | # Source 3 | 4 | 5 | function Get-ServiceHealthDashboard 6 | { 7 |   [CmdletBinding()] 8 |   [OutputType([PSObject])] 9 |   Param 10 |   ( 11 |     [Parameter(Mandatory=$false, 12 |         ValueFromPipelineByPropertyName=$false, 13 |     Position=0)] 14 |     [PSCredential]$Credential, 15 | 16 |     [Parameter(Mandatory=$false, 17 |         ValueFromPipelineByPropertyName=$false, 18 |     Position=1)] 19 |     [switch]$ClearCookie 20 |   ) 21 |   Begin 22 |   { 23 |     If(!($PSVersionTable.PSVersion.Major -ge 3)){ 24 |       Write-Output "Sorry, PowerShell version 3.0 or above is required!" 25 |       break 26 |     } 27 |     function Get-Error { 28 |       Param( 29 |         [Management.Automation.ErrorRecord]$e 30 |       ) 31 |       Begin 32 |       {} 33 |       Process 34 |       { 35 |         $info = [PSCustomObject]@{ 36 |           Exception = $e.Exception.Message 37 |           Reason    = $e.CategoryInfo.Reason 38 |           Target    = $e.CategoryInfo.TargetName 39 |           Script    = $e.InvocationInfo.ScriptName 40 |           Line      = $e.InvocationInfo.ScriptLineNumber 41 |           Column    = $e.InvocationInfo.OffsetInLine 42 |         } 43 |       } 44 |       End 45 |       { 46 |         return $info 47 |       } 48 |     } 49 |     If($ClearCookie){ 50 |       Remove-Variable -Scope global -Name O365cookie -ErrorAction SilentlyContinue 51 |     } 52 |   } 53 |   Process 54 |   { 55 |     # check if cookie exists and prompt for credentials if not 56 |     If(!($global:O365cookie)){ 57 |       Write-Verbose -Message "No O365cookie exist! Need credentials!" 58 |       If(!($Credential)){ 59 |         $Credential = $host.ui.PromptForCredential('Office Credentials', 'Please Enter Your Office 365 Credentials','','') 60 |       } 61 |       # create json payload 62 |       $O365jsonPayload = (@{userName=$Credential.username;password=$Credential.GetNetworkCredential().password;} | convertto-json).tostring() 63 |       # retrieve cookie 64 |       try{ 65 |         $Registration= invoke-restmethod -contenttype "application/json" -method Post -uri "https://api.admin.microsoftonline.com/shdtenantcommunications.svc/Register" -body $O365jsonPayload -ErrorAction Stop 66 |         $global:O365cookie = $Registration.RegistrationCookie 67 |       } 68 |       catch{ 69 |         # get error record 70 |         Get-Error -e $_ 71 |         break 72 |       } 73 |       $O365jsonPayload = (@{lastCookie=$global:O365cookie;locale="en-US";preferredEventTypes=@(0,1,2)} | convertto-json).tostring() 74 |     } 75 |     Else{ 76 |       Write-Verbose -Message "O365cookie exist! Create JsonPayload" 77 |       # insert cookie into payload 78 |       $O365jsonPayload = (@{lastCookie=$global:O365cookie;locale="en-US";preferredEventTypes=@(0,1)} | convertto-json).tostring() 79 |     } 80 |     try{ 81 |       # get events 82 |       $events = (invoke-restmethod -contenttype "application/json" -method Post -uri "https://api.admin.microsoftonline.com/shdtenantcommunications.svc/GetEvents" -body $O365jsonPayload) 83 |     } 84 |     catch{ 85 |       # get error record 86 |       Get-Error -e $_ 87 |     } 88 |   } 89 |   End 90 |   { 91 |     return $events.Events 92 |   } 93 | } -------------------------------------------------------------------------------- /Office365/README.md: -------------------------------------------------------------------------------- 1 | # My Office 365 Scripts 2 | Here's were I keep my Office 365 Scripts 3 | 4 | #License Management 5 | ## Get-msoluserlicensestatus 6 | lists all Office 365 Serviceplans,license options and provisioning status 7 | of these for the specified user status 8 | 9 | # Role Management 10 | ## Get-MsolRoleMemberDetails 11 | This cmdlet lists the members of the Office 365 and Azure Roles 12 | 13 | # User Management 14 | ## Get-MsolUserInformation 15 | The Get-MsolUserInformation cmdlet provides an easy way to retrieve all users that are a member or guest 16 | and or are registered in Azure Directory or Active Directory. In addition a new property is added to the 17 | output called SynchType which is either set to "InCloud" or "ADSynched". 18 | 19 | # Utilities 20 | ## Disable-MsolUserServicePlan.ps1 21 | The Disable-MsolUserServicePlan cmdlet disables an Office 365 Service Plan for the specified user. 22 | 23 | ## Get-Office365AccountSkuLicensedUsers 24 | The Get-Office365AccountSkuLicensedUsers cmdlet retrieves the users that have a specific Office 365 25 | subscription (AccountSkuId) assigned. 26 | 27 | -------------------------------------------------------------------------------- /Office365/RoleManagement/Get-MsolRoleMemberDetails.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Get-MsolRoleMemberDetails 4 | .DESCRIPTION 5 | This cmdlet lists the members of the Office 365 and Azure Roles 6 | .PARAMETER Role 7 | This parameter is optional and allows the selection of a specific Office 365 / Azure Role. 8 | .EXAMPLE 9 | Get-MsolRoleMemberDetails 10 | 11 | Lists all Roles and users that have the role assigned 12 | 13 | .EXAMPLE 14 | Get-MsolRoleMemberDetails -Role Company_Administrator 15 | 16 | List all usres that are have the specified role assigned 17 | .NOTES 18 | Version 1.0, 20.09.2016, Alex Verboon 19 | 20 | #> 21 | function Get-MsolRoleMemberDetails 22 | { 23 | [CmdletBinding()] 24 | 25 | Param() 26 | 27 | DynamicParam { 28 | 29 | $attributes = new-object System.Management.Automation.ParameterAttribute 30 | $attributes.ParameterSetName = "__AllParameterSets" 31 | $attributes.Mandatory = $false 32 | $attributeCollection = new-object -Type System.Collections.ObjectModel.Collection[System.Attribute] 33 | $attributeCollection.Add($attributes) 34 | 35 | Try 36 | { 37 | Get-MsolDomain -ErrorAction Stop > $null 38 | 39 | } 40 | catch 41 | { 42 | write-error "You must call the Connect-MsolService cmdlet before calling any other cmdlets" 43 | Throw 44 | } 45 | 46 | $_Values = ((Get-MsolRole | select-object Name | Sort-object Name).Name) -replace " ","_" 47 | 48 | If ([string]::IsNullOrEmpty($_Values)) 49 | { 50 | Write-Error "No Roles found, check your connectivity to Office365/Azure" 51 | Throw 52 | } 53 | 54 | $ValidateSet = new-object System.Management.Automation.ValidateSetAttribute($_Values) 55 | $attributeCollection.Add($ValidateSet) 56 | $Role = new-object -Type System.Management.Automation.RuntimeDefinedParameter("Role", [string], $attributeCollection) 57 | $paramDictionary = new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary 58 | $paramDictionary.Add("Role", $Role) 59 | return $paramDictionary } 60 | 61 | Begin 62 | { 63 | #checking connectivity again, just in case 64 | Try 65 | { 66 | Get-MsolDomain -ErrorAction Stop > $null 67 | 68 | } 69 | catch 70 | { 71 | if ($cred -eq $null) {$cred = Get-Credential $O365Adminuser} 72 | Write-verbose "Connecting to Office 365" 73 | Connect-MsolService -Credential $cred 74 | } 75 | 76 | if ($PSBoundParameters.ContainsKey("Role")) 77 | { 78 | 79 | $Role = $Role.value -replace "_"," " 80 | write-verbose "Retrieving Role: members for Role $($Role)" 81 | $Roles = Get-MsolRole -RoleName "$($Role)" 82 | } 83 | Else 84 | { 85 | Write-verbose "Retrieving role members for all available roles" 86 | $Roles = Get-MsolRole | Sort-Object Name 87 | } 88 | } 89 | 90 | Process 91 | { 92 | $RoleMemberInfo=@() 93 | ForEach($irole in $Roles) 94 | { 95 | write-verbose $irole.Name 96 | Write-verbose $irole.ObjectId 97 | $members= Get-MsolRoleMember -RoleObjectId $irole.ObjectID 98 | ForEach ($member in $members) 99 | { 100 | $Userinfo = Get-MsolUser -ObjectId $member.ObjectId -ErrorAction SilentlyContinue 101 | $object = New-Object -TypeName PSObject 102 | $object | Add-Member -MemberType NoteProperty -Name "Role" -Value $irole.Name 103 | $object | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $member.DisplayName 104 | $object | Add-Member -MemberType NoteProperty -Name "ObjectID" -Value $UserInfo.ObjectId 105 | $object | Add-Member -MemberType NoteProperty -Name "UserPrincipalName" -Value $UserInfo.UserPrincipalName 106 | $object | Add-Member -MemberType NoteProperty -Name "FirstName" -Value $UserInfo.FirstName 107 | $object | Add-Member -MemberType NoteProperty -Name "LastName" -Value $UserInfo.LastName 108 | $object | Add-Member -MemberType NoteProperty -Name "IsLicensed" -Value $UserInfo.IsLicensed 109 | $RoleMemberInfo += $object 110 | } 111 | } 112 | 113 | } 114 | 115 | End 116 | { 117 | $RoleMemberInfo 118 | } 119 | } 120 | 121 | 122 | 123 | -------------------------------------------------------------------------------- /Office365/Utilities/Disable-MsolUserServicePlan.ps1: -------------------------------------------------------------------------------- 1 | function Disable-MsolUserServicePlan 2 | { 3 | <# 4 | .Synopsis 5 | Disables an Office 365 Service Plan for a user 6 | .DESCRIPTION 7 | The Disable-MsolUserServicePlan cmdlet disables an Office 365 Service Plan for the specified user. 8 | 9 | When assigning an Office 365 E3 license to a user, by default the following Service plans are enabled 10 | 11 | RMS_S_ENTERPRISE, OFFICESUBSCRIPTION,MCOSTANDARD,SHAREPOINTWAC,SHAREPOINTENTERPRISE,EXCHANGE_S_ENTERPRISE 12 | 13 | Azure Rights Management, Office Pro Plus, Skype for Business, Office Web Apps, Sharepoint, Exchange 14 | 15 | Use the Disable-MsolUserServicePlan to disable an individual Service Plan. 16 | 17 | This cmdlet requires the Azure Directory PowerShell module 18 | https://technet.microsoft.com/library/jj151815.aspx#bkmk_installmodule 19 | 20 | Connect to Azure Directory first before using this cmdlet 21 | Connect-MsolService 22 | 23 | 24 | .PARAMETER UserPrincipalName 25 | The user ID of the user to retrieve. 26 | 27 | .PARMAETER ServicePlan 28 | The Service Plan to disable 29 | 30 | .EXAMPLE 31 | Disable-MsolUserServicePlan -UserPrincipalName john.doe@contoso.onmicrosoft.com -ServicePlan SkypeforBusiness 32 | 33 | This command disables Skype for Business for user John Doe 34 | .EXAMPLE 35 | Disable-MsolUserServicePlan -UserPrincipalName john.doe@contoso.onmicrosoft.com -ServicePlan Exchange 36 | 37 | This command disables Exchange for user John Doe 38 | .NOTES 39 | Created by Alex Verboon, 13. Dec. 2015 40 | 41 | https://msdn.microsoft.com/en-us/library/dn568014.aspx 42 | https://technet.microsoft.com/en-us/library/dn771769.aspx 43 | #> 44 | 45 | [CmdletBinding(SupportsShouldProcess=$true)] 46 | Param 47 | ( 48 | 49 | [Parameter(Mandatory=$true, 50 | ValueFromPipelineByPropertyName=$true,HelpMessage="The users office 365 principalname", 51 | Position=0)] 52 | [string]$UserPrincipalName, 53 | 54 | [Parameter(Mandatory=$true, 55 | ParameterSetName = "ServicePlan", 56 | ValueFromPipelineByPropertyName=$true, 57 | Position=1)] 58 | [ValidateSet("SkypeforBusiness","OfficeWebApps","SharePoint","Exchange","OfficeProfessionalPlus","AzureRightsManagement")] 59 | [string]$ServicePlan 60 | ) 61 | 62 | Begin 63 | { 64 | $AccountSkuID = (Get-MsolAccountSku | Where {$_.SkuPartNumber -eq "ENTERPRISEPACK"}).AccountSkuId 65 | 66 | switch($ServicePlan) 67 | { 68 | "SkypeforBusiness" {$planname = "MCOSTANDARD"} 69 | "OfficeWebApps" { $planname = "SHAREPOINTWAC"} 70 | "SharePoint" {$planname = "SHAREPOINTENTERPRISE"} 71 | "Exchange" {$planname = "EXCHANGE_S_ENTERPRISE"} 72 | "OfficeProfessionalPlus" {$planname = "OFFICESUBSCRIPTION"} 73 | "AzureRightsManagement" {$planname = "RMS_S_ENTERPRISE"} 74 | } 75 | Write-Verbose "Selected plan to disable: $planname" 76 | 77 | $ouser = Get-MsolUser -UserPrincipalName $UserPrincipalName -ErrorAction SilentlyContinue 78 | 79 | if ($ouser -ne $null) 80 | { 81 | $ouserlicense = $ouser.Licenses | Select-Object -ExpandProperty ServiceStatus 82 | $DisabledServices = ($ouserlicense | Where-Object -Property ProvisioningStatus -EQ "Disabled").ServicePlan.ServiceName 83 | Write-verbose "Current Disabled Service Plans: $DisabledServices" 84 | $EnabledServices = ($ouserlicense | Where-Object -Property ProvisioningStatus -EQ "Success").ServicePlan.ServiceName 85 | Write-verbose "Current Enabled Service Plans: $EnabledServices" 86 | } 87 | Else 88 | { 89 | Write-Error "User $UserPrincipalName does not exist" 90 | break 91 | } 92 | } 93 | 94 | Process 95 | { 96 | If ($DisabledServices -contains $planname -eq $true) 97 | { 98 | Write-output "The Service plan DisableServicePlan is already disabled for user $UserPrincipalName" 99 | } 100 | Else 101 | { 102 | 103 | If ($DisabledServices.Count -eq 0) 104 | { 105 | $DisabledServicesNew = $planname 106 | } 107 | Else 108 | { 109 | $DisabledServicesNew = {$DisabledServices}.Invoke() 110 | $DisabledServicesNew.Add("$planname") 111 | } 112 | 113 | $LicenseOptions = New-MsolLicenseOptions -AccountSkuId "$AccountSkuID" -DisabledPlans $DisabledServicesNew 114 | Write-Verbose "New Disabled Service Plans: $($LicenseOptions.DisabledServicePlans)" 115 | 116 | If ($PScmdlet.ShouldProcess("Disabling Service Plan $planname for user$UserPrincipalName")) 117 | { 118 | Set-MsolUserLicense -UserPrincipalName "$UserPrincipalName" -LicenseOptions $LicenseOptions 119 | } 120 | } 121 | } 122 | End{} 123 | } 124 | 125 | -------------------------------------------------------------------------------- /Office365/Utilities/Get-Office365AccountSkuLicensedUsers.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Get-Office365AccountSkuLicensedUsers 4 | .DESCRIPTION 5 | The Get-Office365AccountSkuLicensedUsers cmdlet retrieves the users that have a specific Office 365 6 | subscription (AccountSkuId) assigned. 7 | .EXAMPLE 8 | Get-Office365LicenseInfo 9 | 10 | .PARAMETER AccountSkuId 11 | The name of an Office 365 AccountSkuId 12 | 13 | A list of known AccountSkuId's pre-populated. 14 | 15 | Extend the list if needed, a list of known AccountSkuIDs can be found here: 16 | # http://blogs.technet.com/b/treycarlee/archive/2013/11/01/list-of-powershell-licensing-sku-s-for-office-365.aspx 17 | 18 | Other usefull sources related to licensing 19 | # https://technet.microsoft.com/en-us/library/dn771771.aspx 20 | # https://technet.microsoft.com/en-us/library/dn771773.aspx 21 | 22 | Version 1.1 - added ENTERPRISEWITHSCAL license option 23 | 24 | #> 25 | function Get-Office365AccountSkuLicensedUsers 26 | { 27 | [CmdletBinding()] 28 | [Alias()] 29 | Param 30 | ( 31 | # AccountSkuId 32 | [Parameter(Mandatory=$true, 33 | ParameterSetName = "AccountSkuId", 34 | ValueFromPipelineByPropertyName=$true, 35 | Position=0)] 36 | [ValidateSet("ENTERPRISEPACK","RIGHTSMANAGEMENT","AAD_PREMIUM","PLANNERSTANDALONE","POWER_BI_STANDARD","ENTERPRISEWITHSCAL")] 37 | $AccountSkuId 38 | ) 39 | 40 | Begin 41 | { 42 | 43 | } 44 | Process 45 | { 46 | If ($PSBoundParameters.ContainsKey("AccountSkuId")) 47 | { 48 | $AccountSkuIdUsers = Get-MsolUser | Select-Object DisplayName,UserPrincipalName -ExpandProperty Licenses | Where-Object {$_.AccountSkuId -like "*$AccountSkuId*"} 49 | $AccountSkuIdUsers | Select-Object DisplayName,UserPrincipalName 50 | } 51 | } 52 | End 53 | { 54 | 55 | } 56 | } 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /Office365/roadmap/get-office365roadmap.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-Office365Roadmap { 3 | 4 | <# 5 | .Synopsis 6 | Get-Office365Roadmap 7 | .DESCRIPTION 8 | Get-Office365Roadmap retrieves Office 365 information 9 | .EXAMPLE 10 | Get-Office365Roadmap 11 | 12 | Retrieves the complete Office 365 roadmap information 13 | 14 | .EXAMPLE 15 | Get-Office365Roadmap -Stats 16 | 17 | Count Name 18 | ----- ---- 19 | 203 In development 20 | 191 Launched 21 | 17 Previously released 22 | 61 Rolling out 23 | 3 Cancelled 24 | 25 | .PARAMETER Stats 26 | Shows the total number of features grouped by deployment status 27 | 28 | #> 29 | [CmdletBinding()] 30 | Param( 31 | [switch]$Stats 32 | ) 33 | 34 | Begin{} 35 | Process{ 36 | $roadmapfeatures = Invoke-WebRequest -Uri https://roadmap-api.azurewebsites.net/api/features 37 | $features = $roadmapfeatures.Content 38 | $rm = ($features) -join "`n" | ConvertFrom-Json 39 | } 40 | 41 | End{ 42 | If ($Stats -eq $true) 43 | { 44 | $rm | Group-Object Status | Select-Object Count,Name 45 | } 46 | Else 47 | { 48 | $rm 49 | } 50 | } 51 | } 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Office365/wip/Download-SPOFile.ps1: -------------------------------------------------------------------------------- 1 | #Specify variables 2 | 3 | $random = Get-Random -Minimum 1000 -Maximum 10000 4 | 5 | $User = "alex@asiaperf.onmicrosoft.com" 6 | $SiteURL = "https://asiaperf.sharepoint.com" 7 | $URLPath = "/Shared Documents/1Excel40M.xlsx" 8 | $Target = "c:\temp\perf\2Excel40M$random.xlsx" 9 | 10 | #$URLPath.Split("/")[-1] 11 | 12 | #Add references to SharePoint client assemblies 13 | Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" 14 | Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 15 | $Password = Read-Host -Prompt "Please enter your password" -AsSecureString 16 | 17 | Try { 18 | #Bind to site collection 19 | $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) 20 | $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password) 21 | $Context.Credentials = $Creds 22 | } 23 | Catch { 24 | Write-Host "Unable to open Site Collection" $SiteURL -ForegroundColor Red 25 | } 26 | 27 | $TimeTaken = Measure-Command { 28 | Try { 29 | #Download File 30 | Write-Host "Downloading" $URLPath "..." -ForegroundColor Yellow 31 | $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Context,$URLPath) 32 | [System.IO.FileStream] $WriteStream = [System.IO.File]::Open($Target,[System.IO.FileMode]::Create); 33 | $FileInfo.Stream.CopyTo($WriteStream); 34 | 35 | $WriteStream.Close() 36 | } 37 | Catch { 38 | Write-Host "Unable to download file" $SiteURL -ForegroundColor Red 39 | } 40 | } 41 | 42 | $TotalSeconds = [INT]$TimeTaken.TotalSeconds 43 | Write-Host "-Download took" $TotalSeconds "Seconds" -ForegroundColor Green 44 | -------------------------------------------------------------------------------- /Office365/wip/Upload-SPOFile.ps1: -------------------------------------------------------------------------------- 1 | #Specify variables 2 | # https://github.com/brendankarl/Office-365-PowerShell/tree/master/Creating%20Content 3 | # https://www.microsoft.com/en-us/download/details.aspx?id=42038 4 | 5 | 6 | $User = "alex@asiaperf.onmicrosoft.com" 7 | $SiteURL = "https://asiaperf.sharepoint.com" 8 | $DocLibName = "Documents" 9 | $FileName = "C:\temp\perf\1Excel40M.xlsx" 10 | 11 | #Add references to SharePoint client assemblies 12 | Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" 13 | Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 14 | $Password = Read-Host -Prompt "Please enter your password" -AsSecureString 15 | 16 | Try { 17 | #Bind to site collection 18 | $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) 19 | $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password) 20 | $Context.Credentials = $Creds 21 | #Retrieve list 22 | $List = $Context.Web.Lists.GetByTitle($DocLibName) 23 | $Context.Load($List) 24 | $Context.ExecuteQuery() 25 | } 26 | Catch { 27 | Write-Host "Unable to open list" $SiteURL -ForegroundColor Red 28 | } 29 | 30 | $TimeTaken = Measure-Command { 31 | Try { 32 | #Upload file 33 | $File = Get-Item $FileName 34 | Write-Host "Uploading" $File.Name"..." -ForegroundColor Yellow 35 | $FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open) 36 | $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation 37 | $FileCreationInfo.Overwrite = $true 38 | $FileCreationInfo.ContentStream = $FileStream 39 | $FileCreationInfo.URL = $File.Name 40 | $Upload = $List.RootFolder.Files.Add($FileCreationInfo) 41 | $Context.Load($Upload) 42 | $Context.ExecuteQuery() 43 | } 44 | Catch { 45 | Write-Host "Unable to upload file" $File.Name -ForegroundColor Red 46 | } 47 | } 48 | 49 | $TotalSeconds = [INT]$TimeTaken.TotalSeconds 50 | Write-Host "-Upload took" $TotalSeconds "Seconds" -ForegroundColor Green 51 | -------------------------------------------------------------------------------- /Office365/wip/folders.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | #Connect-SPOService -Url https://asiaperf-admin.sharepoint.com -credential $Cred 4 | 5 | Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" 6 | Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 7 | 8 | $SPOUser = "alex@asiaperf.onmicrosoft.com" 9 | # Uses a hardcoded password, use only during test/lab: 10 | $SPOPassword = convertto-securestring "Caba1199" -asplaintext -force 11 | # Better: $SPOPassword = Read-Host -Prompt "Please enter your password" -AsSecureString 12 | $SPOODfBUrl = "https://asiaperf.sharepoint.com" 13 | $SiteURL = "https://asiaperf.sharepoint.com" 14 | 15 | $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SPOODfBUrl) 16 | $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($SPOUser,$SPOPassword) 17 | $Context.RequestTimeout = 16384000 18 | $Context.Credentials = $Credentials 19 | $Context.ExecuteQuery() 20 | 21 | $Web = $Context.Web 22 | $Context.Load($Web) 23 | $Context.ExecuteQuery() 24 | 25 | 26 | $SPODocLibName = "Documents" 27 | $SPOList = $Web.Lists.GetByTitle($SPODocLibName) 28 | $Context.Load($SPOList.RootFolder) 29 | $Context.ExecuteQuery() 30 | 31 | 32 | 33 | 34 | 35 | 36 | <# 37 | $FolderName = "Test1" 38 | $SPOFolder = $SPOList.RootFolder 39 | $NewFolder = $SPOFolder.Folders.Add($FolderName) 40 | $Web.Context.Load($NewFolder) 41 | $Web.Context.ExecuteQuery() 42 | #> 43 | 44 | #Update-FormatData -AppendPath "C:\Data\dev\posh\Office365\SPClient.Format.ps1xml" 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # My PowerShell Code 2 | 3 | Hey there, welcome to my repository. Here's where I store my PowerShell scripts. 4 | 5 | 6 | Comments are always welcome. 7 | 8 | Alex 9 | 10 | www.verboon.info 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Security/CQureCourseNotes/RecoverFiles.ps1: -------------------------------------------------------------------------------- 1 | # How to Recover Deleted Files from the Drive 2 | # https://cqureacademy.com/blog/forensics/how-to-recover-deleted-files-from-the-drive 3 | 4 | -------------------------------------------------------------------------------- /Security/Get-AuditPolicySettings.ps1: -------------------------------------------------------------------------------- 1 | 2 | function Get-AuditPolicySettings 3 | { 4 | <# 5 | .Synopsis 6 | Get-AuditPolicySettings 7 | .DESCRIPTION 8 | This script pulls the audit policy settings for the local machine 9 | .EXAMPLE 10 | Get-AuditPolicySettings 11 | .NOTES 12 | Original script code is from Microsoft, i changed the code so that it displays 13 | the human readable audit policy names instead of the GUIDs. 14 | #> 15 | 16 | [CmdletBinding()] 17 | Param 18 | () 19 | 20 | Begin 21 | { 22 | If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) 23 | { 24 | Echo "This script needs to be run As Admin" 25 | Break 26 | } 27 | } 28 | Process 29 | { 30 | 31 | $auditPolicy = Auditpol /get /category:* /r 32 | $result = @() 33 | 34 | for ($i = 1; $i -lt $auditPolicy.Length; $i++) 35 | { 36 | if($auditPolicy[$i]) 37 | { 38 | $auditPolicyObj = new-object psobject 39 | $splittedStr = $auditPolicy[$i].Split(",") 40 | $PolicyName=$splittedStr[2] 41 | $policyId=$splittedStr[3] 42 | $policyId=$policyId.TrimStart("{}") 43 | $policyId=$policyId.TrimEnd("}") 44 | Add-Member -InputObject $auditPolicyObj -MemberType NoteProperty -Name PolicyName -Value $PolicyName 45 | #Add-Member -InputObject $auditPolicyObj -MemberType NoteProperty -Name PolicyId -Value $policyId 46 | Add-Member -InputObject $auditPolicyObj -MemberType NoteProperty -Name PolicyValue -Value $splittedStr[4] 47 | $result += $auditPolicyObj 48 | } 49 | } 50 | return $result 51 | } 52 | End 53 | { 54 | } 55 | } 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /Security/Get-IscMSSecBulletinInfo.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Get-IscMSSecBulletinInfo 4 | .DESCRIPTION 5 | Get-IscMSSecBulletinInfo retrieves Microsoft Security bulleting information from 6 | the SANS Internet Storm Center DShield Rest API https://isc.sans.edu/api 7 | .EXAMPLE 8 | Get-IscMSSecBulletinInfo -BulletinID MS16-024 9 | 10 | id : 16026 11 | title : Security Update for Graphic Fonts to Address Remote Code Execution 12 | affected : Microsoft Windows, Microsoft .NET Framework 13 | kb : 3143148 14 | exploits : no 15 | severity : critical 16 | clients : critical 17 | servers : critical 18 | 19 | .PARAMETER BulletinID 20 | Microsoft BulletinID Number 21 | Example: MS16-026 22 | 23 | 24 | .NOTES 25 | 1.0 by Alex Verboon, 6/04/2016 26 | #> 27 | function Get-IscMSSecBulletinInfo 28 | { 29 | [CmdletBinding()] 30 | Param 31 | ( 32 | # Param1 help description 33 | [Parameter(Mandatory=$true, 34 | HelpMessage="Enter MS Security Bulletin Number", 35 | ValueFromPipelineByPropertyName=$true, 36 | Position=0)] 37 | $BulletinID 38 | ) 39 | 40 | Begin 41 | { 42 | If ([string]::IsNullOrEmpty($BulletinID)) 43 | { 44 | Write-Output "Microsoft Security Bulletin ID missing" 45 | break 46 | } 47 | $uri = "https://isc.sans.edu/api/getmspatch/$BulletinID" + "?json" 48 | 49 | } 50 | Process 51 | { 52 | $data = Invoke-WebRequest -Uri $uri 53 | $bulletininfo = $data.Content | ConvertFrom-Json | Select-Object -ExpandProperty getmspatch -ErrorAction SilentlyContinue 54 | If ($bulletininfo.kb -eq $null) 55 | { 56 | Write-Output "Bulletin ID $BulletinID not found!" 57 | } 58 | } 59 | End 60 | { 61 | $bulletininfo 62 | } 63 | } 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /Security/Get-MacVendor.ps1: -------------------------------------------------------------------------------- 1 | function Get-MacVendor { 2 | <# 3 | .Synopsis 4 | Resolve MacAddresses To Vendors 5 | .Description 6 | This Function Queries The MacVendors API With Supplied MacAdderess And Returns Manufacturer Information If A Match Is Found 7 | .Parameter MacAddress 8 | MacAddress To Be Resolved 9 | .Example 10 | Get-MacVendor 11 | .Example 12 | Get-MacVendor -MacAddress 00:00:00:00:00:00 13 | .Example 14 | Get-DhcpServerv4Lease -ComputerName $ComputerName -ScopeId $ScopeId | Select -ExpandProperty ClientId | Get-MacVendor 15 | #> 16 | [CmdletBinding()] 17 | param( 18 | [Parameter (Mandatory=$true, 19 | ValueFromPipeline=$true)] 20 | [ValidatePattern("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$")] 21 | [string[]]$MacAddress 22 | ) 23 | process{ 24 | foreach($Mac in $MacAddress){ 25 | try{ 26 | Write-Verbose 'Sending Request to http://api.macvendors.com' 27 | Invoke-RestMethod -Method Get -Uri http://api.macvendors.com/$Mac -ErrorAction SilentlyContinue | Foreach-object { 28 | 29 | [pscustomobject]@{ 30 | Vendor = $_ 31 | MacAddress = $Mac 32 | } 33 | } 34 | } 35 | catch{ 36 | Write-Warning -Message "$Mac, $_" 37 | } 38 | } 39 | } 40 | end{} 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Security/MsrcSecurityUpdates_samples.ps1: -------------------------------------------------------------------------------- 1 |  2 | $apikey = "" 3 | Set-MSRCApiKey -ApiKey $apikey 4 | 5 | 6 | #https://sqljana.wordpress.com/2017/08/31/powershell-get-security-updates-list-from-microsoft-by-monthproductkbcve-with-api/ 7 | 8 | 9 | $id = Get-MsrcCvrfDocument -ID '2017-Dec' 10 | 11 | 12 | $affsw = Get-MsrcCvrfAffectedSoftware -Vulnerability $id.Vulnerability -ProductTree $id.ProductTree 13 | $affsw 14 | $affsw | Where-Object {$_.fullproductname -match "1709"} 15 | 16 | $cvesum = Get-MsrcCvrfCVESummary -Vulnerability $id.Vulnerability -ProductTree $id.ProductTree 17 | $cvesum | Where-Object {$_."Affected Software" -match "1709"} 18 | 19 | $explind = Get-MsrcCvrfExploitabilityIndex -Vulnerability $id.Vulnerability 20 | 21 | Get-MsrcVulnerabilityReportHtml -Vulnerability $id.Vulnerability -ProductTree $id.ProductTree 22 | Out-File -FilePath "C:\temp\$($id.documenttitle).html" 23 | Invoke-Item -Path "C:\temp\$($id.documenttitle).html" 24 | -------------------------------------------------------------------------------- /Security/README.MD: -------------------------------------------------------------------------------- 1 | # PowerShell Scripts for security related stuff 2 | 3 | ## Get-IscMSSecBulletinInfo 4 | Get-IscMSSecBulletinInfo retrieves Microsoft Security bulleting information from 5 | the SANS Internet Storm Center DShield Rest API https://isc.sans.edu/api 6 | 7 | -------------------------------------------------------------------------------- /Security/SecurityPolicyScript.ps1: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------ 2 | # Copyright (c) Microsoft Corporation. All rights reserved. 3 | #------------------------------------------------------------------------------ 4 | # This script pulls securty policy settings for this machine and parse it to objects with the following members: 5 | # SectionName 6 | # SettingName 7 | # SettingValue 8 | # return the list of these objects 9 | 10 | #random output file name for each run 11 | $tmpFileGuid = [guid]::NewGuid() 12 | $outputFilePath = "$tmpFileGuid.inf" 13 | 14 | # "Start running get security policy command" 15 | secedit /export /areas USER_RIGHTS /cfg $outputFilePath > $null 16 | 17 | 18 | if($LASTEXITCODE -ne 0){ 19 | throw [System.InvalidOperationException] "Secedt failed with error code $LASTEXITCODE" 20 | } 21 | 22 | # "Pulling content from output file: $outputFilePath" 23 | $content = Get-Content $outputFilePath 24 | 25 | 26 | 27 | #retry 3 times to delete the temporary output file (with 5 seconds sleep between retries). 28 | # If failed to delete - throw exception and fail the run. 29 | $retryCount = 3 30 | for($i=1; $i -le $retryCount; $i++) 31 | { 32 | # "Removing output file: $outputFilePath" 33 | Remove-Item $outputFilePath 34 | 35 | if(Test-Path $outputFilePath){ 36 | if($i -eq $retryCount){ 37 | throw [System.InvalidOperationException] "Failed to delete file $outputFilePath after $retryCount retries" 38 | } 39 | Start-Sleep -s 5 40 | } 41 | else{ 42 | break 43 | } 44 | } 45 | 46 | $result = @() 47 | $currentPolicyGroup = "" 48 | 49 | # "Start parsing content" 50 | foreach ($line in $content){ 51 | $securityPolicyObj = new-object psobject 52 | 53 | if($line.StartsWith("[")){ 54 | $line=$line.TrimStart("[") 55 | $line=$line.TrimEnd("]") 56 | $currentPolicyGroup = $line 57 | } 58 | else{ 59 | $splittedSetting = $line.Split("=") 60 | if($splittedSetting.length -ne 2){ 61 | throw "Security settings output is not in the correct format" 62 | } 63 | $policyKey = [guid]::NewGuid() 64 | $settingName = $splittedSetting[0].TrimEnd(" ") 65 | $settingValue = $splittedSetting[1].TrimStart(" ") 66 | Add-Member -InputObject $securityPolicyObj -MemberType NoteProperty -Name SectionName -Value $currentPolicyGroup 67 | Add-Member -InputObject $securityPolicyObj -MemberType NoteProperty -Name SettingName -Value $settingName 68 | Add-Member -InputObject $securityPolicyObj -MemberType NoteProperty -Name SettingValue -Value $settingValue 69 | Add-Member -InputObject $securityPolicyObj -MemberType NoteProperty -Name PolicyKey -Value $policyKey 70 | $result += $securityPolicyObj 71 | } 72 | } 73 | 74 | # "Finished getting and parsing security policy" 75 | #return $result 76 | $result | fl 77 | -------------------------------------------------------------------------------- /Security/defender/Add-DefenderHyperVExclusion.ps1: -------------------------------------------------------------------------------- 1 | function Add-DefenderHyperVExclusions { 2 | <# 3 | .SYNOPSIS 4 | Add-DefenderHyperVExclusions 5 | .DESCRIPTION 6 | Add-DefenderHyperVExclusions adds recommended file extensinos, folders 7 | and processs for the Hyper-V Role to the Defender Exclusion configuration. 8 | 9 | File type exclusions: 10 | *.vhd 11 | *.vhdx 12 | *.avhd 13 | *.avhdx 14 | *.vsv 15 | *.iso 16 | *.rct 17 | *.vmcx 18 | *.vmrs 19 | 20 | Folder exclusions: 21 | %ProgramData%\Microsoft\Windows\Hyper-V 22 | %ProgramFiles%\Hyper-V 23 | %SystemDrive%\ProgramData\Microsoft\Windows\Hyper-V\Snapshots 24 | %Public%\Documents\Hyper-V\Virtual Hard Disks 25 | 26 | Process exclusions: 27 | %systemroot%\System32\Vmms.exe 28 | %systemroot%\System32\Vmwp.exe 29 | 30 | .EXAMPLE 31 | PS C:\> Add-DefenderHyperVExclusions 32 | 33 | The above command adds all recommended Defender Hyper-V exclusions. 34 | .NOTES 35 | 1.0.0 - 16.05.2018 alex verboon 36 | 37 | Recommended exclusions reference: 38 | https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-antivirus/configure-server-exclusions-windows-defender-antivirus 39 | #> 40 | 41 | [cmdletbinding(SupportsShouldProcess)] 42 | param ( 43 | ) 44 | 45 | begin { 46 | # Check if we're running elevated 47 | [bool]$elevated = $false 48 | $elevated = (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") 49 | If ($elevated -eq $false) 50 | { 51 | Write-Error "This script must be run from an elevated process." -ErrorAction Stop 52 | } 53 | 54 | # File Exclusions 55 | $Hv_Extensions = @( 56 | "*.vhd","*.vhdx","*.avhd","*.avhdx","*.vsv","*.iso","*.rct","*.vmcx","*.vmrs" 57 | ) 58 | # Path Exclusions 59 | $HV_Path = @( 60 | "%ProgramData%\Microsoft\Windows\Hyper-V", 61 | "%ProgramFiles%\Hyper-V", 62 | "%SystemDrive%\ProgramData\Microsoft\Windows\Hyper-V\Snapshots", 63 | "%Public%\Documents\Hyper-V\Virtual Hard Disks" 64 | ) 65 | 66 | # Process Exclusions 67 | $HV_Process = @( 68 | "%systemroot%\System32\Vmms.exe" 69 | "%systemroot%\System32\Vmwp.exe" 70 | ) 71 | } 72 | 73 | process { 74 | if ($PSCmdlet.ShouldProcess("local Defender Configuration" , "Adding Hyper-V Exclusions")) { 75 | Try{ 76 | Write-Verbose "Adding Defender Exclusions for Hyper-V" 77 | Add-MpPreference -ExclusionProcess $HV_Process -ExclusionPath $HV_Path -ExclusionExtension $Hv_Extensions 78 | } 79 | Catch{ 80 | Write-Error "An error occoured adding Defender Exclusions for Hyper-V" -ErrorAction Stop 81 | } 82 | } 83 | } 84 | 85 | end { 86 | If ($PSBoundParameters.Keys -contains "verbose") 87 | { 88 | Write-Verbose "Configured Defender Exclusions" 89 | $WDPref = Get-MpPreference 90 | Write-Verbose "Excluded Extensions $($WDPref.ExclusionExtension)" 91 | Write-Verbose "Excluded Paths $($WDPref.ExclusionPath)" 92 | Write-Verbose "Excluded Paths $($WDPref.ExclusionProcess)" 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /Security/defender/Remove-DefenderHyperVExclusion.ps1: -------------------------------------------------------------------------------- 1 | function Remove-DefenderHyperVExclusions { 2 | <# 3 | .SYNOPSIS 4 | Remove-DefenderHyperVExclusions 5 | .DESCRIPTION 6 | Remove-DefenderHyperVExclusions removes recommended file extensinos, folders 7 | and processs for the Hyper-V Role from the Defender Exclusion configuration. 8 | 9 | File type exclusions: 10 | *.vhd 11 | *.vhdx 12 | *.avhd 13 | *.avhdx 14 | *.vsv 15 | *.iso 16 | *.rct 17 | *.vmcx 18 | *.vmrs 19 | 20 | Folder exclusions: 21 | %ProgramData%\Microsoft\Windows\Hyper-V 22 | %ProgramFiles%\Hyper-V 23 | %SystemDrive%\ProgramData\Microsoft\Windows\Hyper-V\Snapshots 24 | %Public%\Documents\Hyper-V\Virtual Hard Disks 25 | 26 | Process exclusions: 27 | %systemroot%\System32\Vmms.exe 28 | %systemroot%\System32\Vmwp.exe 29 | 30 | .EXAMPLE 31 | PS C:\> Remove-DefenderHyperVExclusions 32 | 33 | The above command removes all recommended Hyper-V Defender exclusions. 34 | .NOTES 35 | 1.0.0 - 16.05.2018 alex verboon 36 | 37 | Recommended exclusions reference: 38 | https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-antivirus/configure-server-exclusions-windows-defender-antivirus 39 | #> 40 | 41 | [cmdletbinding(SupportsShouldProcess)] 42 | param ( 43 | ) 44 | 45 | begin { 46 | # Check if we're running elevated 47 | [bool]$elevated = $false 48 | $elevated = (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") 49 | If ($elevated -eq $false) 50 | { 51 | Write-Error "This script must be run from an elevated process." -ErrorAction Stop 52 | } 53 | 54 | # File Exclusions 55 | $Hv_Extensions = @( 56 | "*.vhd","*.vhdx","*.avhd","*.avhdx","*.vsv","*.iso","*.rct","*.vmcx","*.vmrs" 57 | ) 58 | # Path Exclusions 59 | $HV_Path = @( 60 | "%ProgramData%\Microsoft\Windows\Hyper-V", 61 | "%ProgramFiles%\Hyper-V", 62 | "%SystemDrive%\ProgramData\Microsoft\Windows\Hyper-V\Snapshots", 63 | "%Public%\Documents\Hyper-V\Virtual Hard Disks" 64 | ) 65 | 66 | # Process Exclusions 67 | $HV_Process = @( 68 | "%systemroot%\System32\Vmms.exe" 69 | "%systemroot%\System32\Vmwp.exe" 70 | ) 71 | } 72 | 73 | process { 74 | if ($PSCmdlet.ShouldProcess("local Defender Configuration" , "Removing Hyper-V Exclusions")) { 75 | Try{ 76 | Write-Verbose "Removing Defender Exclusions for Hyper-V" 77 | Add-MpPreference -ExclusionProcess $HV_Process -ExclusionPath $HV_Path -ExclusionExtension $Hv_Extensions 78 | } 79 | Catch{ 80 | Write-Error "An error occoured removnig Defender Exclusions for Hyper-V" -ErrorAction Stop 81 | } 82 | } 83 | } 84 | 85 | end { 86 | If ($PSBoundParameters.Keys -contains "verbose") 87 | { 88 | Write-Verbose "Configured Defender Exclusions" 89 | $WDPref = Get-MpPreference 90 | Write-Verbose "Excluded Extensions $($WDPref.ExclusionExtension)" 91 | Write-Verbose "Excluded Paths $($WDPref.ExclusionPath)" 92 | Write-Verbose "Excluded Paths $($WDPref.ExclusionProcess)" 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /Security/install-powersploit.ps1: -------------------------------------------------------------------------------- 1 | ## 2 | ## Use the below commands to install the PowerSploit module 3 | ## 4 | 5 | # add an exclusion path for defender, otherwise files will be removed as they look like malware 6 | # well, in fact they could be right :-) 7 | Set-MpPreference -ExclusionPath "C:\Program Files\WindowsPowerShell\Modules\PowerSploit\" 8 | # Disable defender 9 | Set-MpPreference -DisableRealtimeMonitoring $true 10 | # check the exclusionpath , should include the path set previously 11 | Get-MpPreference | Select-Object -ExpandProperty Exclusionpath 12 | # install the powersploit package 13 | find-package powersploit | Install-Package 14 | # Turn on defender again 15 | Set-MpPreference -DisableRealtimeMonitoring $false 16 | 17 | -------------------------------------------------------------------------------- /Security/networking course/notes.md: -------------------------------------------------------------------------------- 1 | 2 | # The TCP Three-Way Handshake 3 | 4 | -------------------------------------------------------------------------------- /Security/pslogs.ps1: -------------------------------------------------------------------------------- 1 | # Module Logging 2 | $PSModuleLogs = @{ProviderName = "Microsoft-Windows-PowerShell";ID=4100,4103} 3 | $s= Get-WinEvent -FilterHashtable $PSModuleLogs -MaxEvents 50 4 | 5 | # Script Block logging 6 | $PSScriptBlocklogs = @{ProviderName = "Microsoft-Windows-PowerShell";ID=4104,4105,4106} 7 | $x = Get-WinEvent -FilterHashtable $PSScriptBlocklogs -MaxEvents 50 8 | 9 | # all 10 | $PSLogs = @{ProviderName = "Microsoft-Windows-PowerShell";ID=4100,4103,4104,4105,4106,24579,24577} 11 | $logs = Get-WinEvent -FilterHashtable $PSLogs -MaxEvents 100 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Various/Get-IgniteSessions.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-IgniteSessions 3 | { 4 | 5 | #https://gallery.technet.microsoft.com/Ignite-2016-Slidedeck-and-296df316 6 | $Ignite2016ContentRssMaxNumber = 1750 7 | $Ignite2016ContentRss = "https://techcommunity.microsoft.com/gxcuf89792/rss/message?board.id=MicrosoftIgniteContent&message.id=" 8 | $result = @() 9 | [int]$start = 1 10 | $i = 1 11 | 12 | $sw = [System.Diagnostics.Stopwatch]::StartNew() 13 | Write-Progress -Activity "Retrieving Ignite Sessions" -Status "Processing $i of $($Ignite2016ContentRssMaxNumber)" -PercentComplete (($i / $Ignite2016ContentRssMaxNumber) * 100) 14 | 15 | for ($i = $Start; $i -lt $Ignite2016ContentRssMaxNumber; $i++) { 16 | $IgniteMessage = Invoke-WebRequest -Uri "$($Ignite2016ContentRss)$i" 17 | $IgniteMessage = [xml]$IgniteMessage 18 | $object = new-object psobject 19 | Add-Member -InputObject $object -MemberType NoteProperty -Name Title -Value $IgniteMessage.rss.FirstChild.title 20 | Add-Member -InputObject $object -MemberType NoteProperty -Name Link -Value $IgniteMessage.rss.FirstChild.Link 21 | $result += $object 22 | 23 | if ($sw.Elapsed.TotalMilliseconds -ge 5000) 24 | { 25 | $curmemusage = "$('{0:n2}' -f ([double](Get-Process -Id $pid).WorkingSet/1MB)) MB" 26 | Write-Progress -Activity "Retrieving Ignite Sessions" -Status "Processing $i of $($Ignite2016ContentRssMaxNumber)" -PercentComplete (($i / $Ignite2016ContentRssMaxNumber) * 100) 27 | $sw.Reset(); $sw.Start() 28 | } 29 | } 30 | return $result 31 | } 32 | 33 | #$session = Get-IgniteSessions 34 | 35 | #$isession | Select-Object Title,link | Export-Csv -Path C:\data\dev\posh\Various\ignitesessions.txt -Delimiter ";" 36 | 37 | 38 | #$savedsesions = Get-Content -Path C:\data\dev\posh\Various\ignitesessions.txt 39 | 40 | $sel = $savedsesions | Out-GridView -OutputMode Single 41 | 42 | start-process $sel.Split(";")[1] 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Various/Get-oldDODhostswhois.ps1: -------------------------------------------------------------------------------- 1 |  2 | Function Get-oldDODhostswhois{ 3 | 4 | [CmdletBinding()] 5 | Param( 6 | 7 | ) 8 | 9 | 10 | 11 | Begin{ 12 | 13 | Write-Verbose "Retrieve content from DoD Internet Host Table March 1985" 14 | $oldhostsfile = (Invoke-WebRequest -Uri "http://pdp-10.trailing-edge.com/tops20_v6_1_tcpip_installation_tp_ft6/06/new-system/hosts.txt").content 15 | $oldhostsfile | Out-File -FilePath c:\temp\oldhostsfile.txt -Force 16 | 17 | 18 | $hostsfile = Get-Content -Path c:\temp\oldhostsfile.txt 19 | $regex = [regex] "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" 20 | $total = $hostsfile.count 21 | $linecnt = 1 22 | 23 | } 24 | 25 | Process{ 26 | 27 | $Result = @() 28 | ForEach ($con in $hostsfile) 29 | { 30 | 31 | $ipaddresses = $regex.Matches($con) 32 | 33 | ForEach ($ip in $ipaddresses) 34 | { 35 | write-verbose "Processing $($ip)" 36 | $ipaddr = "$($_.value)" 37 | 38 | Try{ 39 | Write-verbose "Retrieving Whois Data for $($ip)" 40 | $whois = Invoke-RestMethod -uri "http://whois.arin.net/rest/ip/$($ip)" 41 | } 42 | Catch{ 43 | $whois = $null 44 | } 45 | 46 | <# 47 | Try{ 48 | Write-verbose "Retrieving Remote Host name for $($_.value)" 49 | $hostname = [system.net.dns]::GetHostByAddress(" $($_.value)") 50 | } 51 | Catch{ 52 | $hostname = $null 53 | } 54 | #> 55 | 56 | $object = [ordered]@{ 57 | IP = $ip 58 | WhoisName = $whois.net.orgRef.name 59 | Whoishandle = $whois.net.orgref.Handle 60 | Whoisregdate = $whois.net.registrationDate 61 | WhoisupdateDate = $whois.net.updateDate 62 | whoisendaddress = $whois.net.endAddress 63 | whoisnetblockdescr = $whois.net.netBlocks.netBlock.description 64 | whoisnetblockthype = $whois.net.netBlocks.netBlock.type 65 | whoisnetblockcidrLength = $whois.net.netBlocks.netBlock.cidrLength 66 | } 67 | $Result += (New-Object -TypeName PSObject -Property $object) 68 | $linecnt++ 69 | Write-verbose "Line: $linecnt / $total" 70 | } 71 | } 72 | 73 | 74 | } 75 | 76 | End{ 77 | $Result 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Various/anothertest.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | ForEach ($Event in $events) { 4 | # Convert the event to XML 5 | $eventXML = [xml]$Event.ToXml() 6 | # Iterate through each one of the XML message properties 7 | For ($i=0; $i -lt $eventXML.Event.EventData.Data.Count; $i++) { 8 | # Append these as object properties 9 | 10 | write-host $eventXML.Event.EventData.Data[$i].name 11 | write-host $eventXML.Event.EventData.Data[$i].'#text' 12 | 13 | 14 | 15 | #Add-Member -InputObject $Event -MemberType NoteProperty -Name $eventXML.Event.EventData.Data[$i].name -Value $eventXML.Event.EventData.Data[$i].'#text' -Force 16 | } 17 | } -------------------------------------------------------------------------------- /Various/binarystuff.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | # binary stuff 4 | $b = 10101001 01000110 11100001 5 | $k = 11111011 00001111 10110101 6 | 7 | $R = 01010010 01001001 01010100 8 | 9 | #> 10 | 11 | $a = 01010010 12 | 13 | -join(-split$a|%{[char][convert]::toint32($_,2)}) 14 | -------------------------------------------------------------------------------- /Various/convertascidecbin.ps1: -------------------------------------------------------------------------------- 1 |  2 | ## Convert ASCI to Decimal and Binary 3 | 4 | $KeyAsci = "J" 5 | $enc = [System.Text.Encoding]::ASCII 6 | $Decimal = $enc.GetBytes("$keyAsci") 7 | Write-host "Key Decimal: $Decimal" 8 | $result =[convert]::ToString("$Decimal",2) 9 | write-host "Key Binary: $result" 10 | 11 | 12 | $random = "1100010" 13 | write-host "Random: $random" 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Various/findwmi.ps1: -------------------------------------------------------------------------------- 1 |  2 | # search wmi for property name specified 3 | 4 | $SearchString = "onedrive" 5 | 6 | 7 | foreach($class in gwmi -namespace "root\cimv2" -list) 8 | { 9 | foreach($property in $class.Properties) 10 | { 11 | if($property.Name.Contains("$SearchString")) 12 | { 13 | $class.Name + ' --- ' + $property.Name 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Various/geofun.ps1: -------------------------------------------------------------------------------- 1 |  2 | $target = "www.verboon.info" 3 | 4 | Function Get-GeoIP { 5 | param ( 6 | [string]$IP 7 | ) 8 | ([xml](Invoke-WebRequest "http://freegeoip.net/xml/$IP").Content).Response 9 | } 10 | 11 | 12 | $trcroutedata = Test-NetConnection -ComputerName $target -TraceRoute -InformationLevel Detailed 13 | 14 | $details = @() 15 | ForEach ($ip in $trcroutedata.TraceRoute) 16 | { 17 | Write-host "Retrieving details for $ip" 18 | $geoip = Get-GeoIP -IP "$ip" 19 | 20 | $object = @{ 21 | IP = $geoip.IP 22 | CountryCode = $geoip.CountryCode 23 | CountryName = $geoip.CountryName 24 | RegionCode = $geoip.RegionCode 25 | RegionName = $geoip.RegionName 26 | City = $geoip.City 27 | ZipCode = $geoip.ZipCode 28 | TimeZone = $geoip.TimeZone 29 | } 30 | $details += (New-Object -TypeName PSObject -Property $object) 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Various/get-eventidsforprovider.ps1: -------------------------------------------------------------------------------- 1 |  2 | # list all possible event IDs for an event provider 3 | # https://blogs.technet.microsoft.com/pie/2016/11/05/list-all-possible-security-events-and-their-descriptions-in-powershell/ 4 | # https://blogs.technet.microsoft.com/ashleymcglone/2013/08/28/powershell-get-winevent-xml-madness-getting-details-from-event-logs/ 5 | 6 | 7 | 8 | (Get-WinEvent -ListProvider "Microsoft-Windows-PowerShell").Events | ` 9 | Select-Object @{Name='Id';Expression={$_.Id -band 0xffffff}}, Description, @{Name='Parameters';Expression={($_.Template).template.data}} | ` 10 | Out-GridView -Title "Audit Event IDs" -PassThru | ` 11 | Format-List 12 | 13 | 14 | 15 | # List all event providers 16 | Get-WinEvent -ListProvider * | Format-Table 17 | 18 | # List all policy-related event providers. 19 | Get-WinEvent -ListProvider *policy* | Format-Table 20 | 21 | # List the logs on the machine where the name is like 'policy' 22 | Get-WinEvent -ListLog *policy* 23 | 24 | # List all possible event IDs and descriptions for the provider 25 | (Get-WinEvent -ListProvider Microsoft-Windows-GroupPolicy).Events | 26 | Format-Table id, description -AutoSize 27 | 28 | # List all of the event log entries for the provider 29 | Get-WinEvent -LogName Microsoft-Windows-GroupPolicy/Operational 30 | 31 | # Each event in each provider has its own message data schema. 32 | # Use this line to find the of each event ID. 33 | # For a specific event 34 | (Get-WinEvent -ListProvider Microsoft-Windows-PowerShell).Events | 35 | Where-Object {$_.Id -eq 4103} 36 | 37 | # For a keyword in the event data 38 | (Get-WinEvent -ListProvider Microsoft-Windows-GroupPolicy).Events | 39 | Where-Object {$_.Template -like "*reason*"} 40 | 41 | # Find an event ID across all ETW providers: 42 | Get-WinEvent -ListProvider * | 43 | ForEach-Object { $_.Events | Where-Object {$_.ID -eq 4168} } -------------------------------------------------------------------------------- /Various/localposhrepo.ps1: -------------------------------------------------------------------------------- 1 |  2 | # https://kevinmarquette.github.io/2017-05-30-Powershell-your-first-PSScript-repository/ 3 | 4 | 5 | # Local PowerShell Repo 6 | $Path = '\\alve01\PoshRepo' 7 | 8 | $repo = @{ 9 | Name = 'MyRepository' 10 | SourceLocation = $Path 11 | PublishLocation = $Path 12 | InstallationPolicy = 'Trusted' 13 | } 14 | Register-PSRepository @repo 15 | 16 | $env:PSModulePath 17 | 18 | Publish-Module -Name GroupPolicyxTended -Repository "MyRepository" 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Various/modula.ps1: -------------------------------------------------------------------------------- 1 | # playing with modula 2 | 3 | 4 | $i1 = 4 5 | $im = 18 6 | 7 | 8 | $pPrivate = 132 9 | $p = [math]::Pow($i1,$pPrivate) 10 | $rp = $p % $im 11 | write-host "Alice: $rp" -ForegroundColor Yellow 12 | 13 | $aPrivate = 152 14 | $a = [math]::Pow($i1,$aPrivate) 15 | $ra = $a % $im 16 | Write-Host "Bob" $ra -ForegroundColor Yellow 17 | 18 | $rResult = [math]::Pow($ra,$pPrivate) % $im 19 | $aResult = [math]::Pow($rp,$aPrivate) % $im 20 | 21 | write-host "$rResult -- $aResult" 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Various/nat.ps1: -------------------------------------------------------------------------------- 1 | #http://www.thomasmaurer.ch/2015/12/how-to-remote-manage-your-nano-server-using-powershell/ 2 | #https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/03/24/using-rras-to-enable-wireless-with-hyper-v/ 3 | #https://msdn.microsoft.com/en-us/virtualization/hyperv_on_windows/user_guide/setup_nat_network 4 | #http://www.thomasmaurer.ch/2015/11/nested-virtualization-in-windows-server-2016-and-windows-10/ 5 | 6 | 7 | 8 | #NAT 9 | 10 | New-VMSwitch -SwitchName "NATSwitch" -SwitchType Internal 11 | Get-NetAdapter 12 | New-NetIPAddress -IPAddress 192.168.10.1 -PrefixLength 24 -InterfaceIndex 48 13 | New-NetNat -Name MyNATnetwork -InternalIPInterfaceAddressPrefix 192.168.10.0/24 14 | 15 | # ps remote nano 16 | Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" 17 | 18 | 19 | #nested virtualization 20 | Set-VMProcessor -VMName SRV2016 -ExposeVirtualizationExtensions $true 21 | Get-VMNetworkAdapter -VMName srv2016 | Set-VMNetworkAdapter -MacAddressSpoofing On 22 | 23 | 24 | -------------------------------------------------------------------------------- /Various/oldhostsfile.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexverboon/posh/6d6f28883b14bf62e89932b1ab209cbfba6768b5/Various/oldhostsfile.txt -------------------------------------------------------------------------------- /Various/pslogs.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | $pslogs = Get-WinEvent -FilterHashtable @{ ProviderName="Microsoft-Windows-PowerShell"; Id = 4103,4104,4105,4106 } 4 | 5 | #$a = Get-WinEvent -FilterHashtable @{ ProviderName="Microsoft-Windows-PowerShell"; Id = 4103 } 6 | $b = Get-WinEvent -FilterHashtable @{ ProviderName="Microsoft-Windows-PowerShell"; Id = 4104 } 7 | #$c = Get-WinEvent -FilterHashtable @{ ProviderName="Microsoft-Windows-PowerShell"; Id = 4105 } 8 | $d = Get-WinEvent -FilterHashtable @{ ProviderName="Microsoft-Windows-PowerShell"; Id = 4106 } 9 | 10 | $pslogs |Select-Object * | sort-Object ActivityID | fl 11 | -------------------------------------------------------------------------------- /Various/whois_hosts.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexverboon/posh/6d6f28883b14bf62e89932b1ab209cbfba6768b5/Various/whois_hosts.txt -------------------------------------------------------------------------------- /Various/wmiexploration.ps1: -------------------------------------------------------------------------------- 1 |  2 | # Dump WMI Classes 3 | $NameSpaces = Get-CimInstance -Namespace root -ClassName __NAMESPACE | Where-Object {$_.Name -eq "CIMV2"} 4 | 5 | ForEach ($ns in $NameSpaces) 6 | { 7 | write-host "$($ns.name)" -ForegroundColor Green 8 | $classes = Get-CimClass -Namespace "root/$($ns.name)" 9 | 10 | ForEach ($cl in $classes) 11 | { 12 | if ($cl.CimClassName -like "CIM_*") 13 | { 14 | Write-host "skipping CIM__ $($cl.CimClassName)" -ForegroundColor DarkBlue 15 | } 16 | Else 17 | { 18 | 19 | Get-CimInstance -Namespace "root/$($ns.name)" -ClassName "$($cl.CimClassName)" | fl 20 | write-host "$($ns.name)" -ForegroundColor Cyan 21 | write-host "$($cl.cimClassname)" -ForegroundColor Yellow 22 | pause 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Windows10/AppCompat/Start-AppCert.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexverboon/posh/6d6f28883b14bf62e89932b1ab209cbfba6768b5/Windows10/AppCompat/Start-AppCert.ps1 -------------------------------------------------------------------------------- /Windows10/BIOS_UEFI/get-biostype.ps1: -------------------------------------------------------------------------------- 1 | 2 | # Source: https://gallery.technet.microsoft.com/scriptcenter/Determine-UEFI-or-Legacy-7dc79488 3 | 4 | 5 | Function Get-BiosType { 6 | 7 | <# 8 | .Synopsis 9 | Determines underlying firmware (BIOS) type and returns an integer indicating UEFI, Legacy BIOS or Unknown. 10 | Supported on Windows 8/Server 2012 or later 11 | .DESCRIPTION 12 | This function uses a complied Win32 API call to determine the underlying system firmware type. 13 | .EXAMPLE 14 | If (Get-BiosType -eq 1) { # System is running UEFI firmware... } 15 | .EXAMPLE 16 | Switch (Get-BiosType) { 17 | 1 {"Legacy BIOS"} 18 | 2 {"UEFI"} 19 | Default {"Unknown"} 20 | } 21 | .OUTPUTS 22 | Integer indicating firmware type (1 = Legacy BIOS, 2 = UEFI, Other = Unknown) 23 | .FUNCTIONALITY 24 | Determines underlying system firmware type 25 | #> 26 | 27 | [OutputType([UInt32])] 28 | Param() 29 | 30 | Add-Type -Language CSharp -TypeDefinition @' 31 | 32 | using System; 33 | using System.Runtime.InteropServices; 34 | 35 | public class FirmwareType 36 | { 37 | [DllImport("kernel32.dll")] 38 | static extern bool GetFirmwareType(ref uint FirmwareType); 39 | 40 | public static uint GetFirmwareType() 41 | { 42 | uint firmwaretype = 0; 43 | if (GetFirmwareType(ref firmwaretype)) 44 | return firmwaretype; 45 | else 46 | return 0; // API call failed, just return 'unknown' 47 | } 48 | } 49 | '@ 50 | 51 | 52 | [FirmwareType]::GetFirmwareType() 53 | } -------------------------------------------------------------------------------- /Windows10/PowerManagement/Get-BatteryChargeStatus.ps1: -------------------------------------------------------------------------------- 1 |  2 | function Get-BatteryChargeStatus 3 | { 4 | <# 5 | .Synopsis 6 | Get-BatteryChargeStatus 7 | .DESCRIPTION 8 | Get-BatteryChargeStatus shows the Battery Charging status, 9 | the remaining Battery capacity in percent and if the system 10 | is running on Battery. 11 | 12 | The Battery Status can have one of the following values: 13 | Charging, Discharging, Idle or NotPresent 14 | .PARAMETER Detail 15 | Displays additional Battery Information 16 | 17 | .EXAMPLE 18 | Get-BatteryChargeStatus 19 | 20 | Status Utilization PowerOnline 21 | ------ ----------- ----------- 22 | Charging 99 True 23 | 24 | 25 | .EXAMPLE 26 | Get-BatteryChargeStatus -Detail 27 | 28 | ChargeRateInMilliwatts : 3052 29 | DesignCapacityInMilliwattHours : 68902 30 | FullChargeCapacityInMilliwattHours : 70222 31 | RemainingCapacityInMilliwattHours : 69689 32 | Status : Charging 33 | Utilization : 99 34 | PowerOnline : True 35 | 36 | .NOTES 37 | 30/07/2017, Initial version, Alex Verboon 38 | 01/08/2017, added class init to check that Windows.Device class is available. 39 | 40 | For more information see: 41 | https://docs.microsoft.com/en-us/uwp/api/windows.devices.power.batteryreport 42 | 43 | #> 44 | [CmdletBinding()] 45 | Param 46 | ( 47 | [switch]$Detail 48 | ) 49 | 50 | Begin 51 | { 52 | Try{ 53 | # First ensure Windows.Devices class is available 54 | $BattAssembly = [Windows.Devices.Power.Battery,Windows.Devices.Power.Battery,ContentType=WindowsRuntime] 55 | #[Windows.Devices.Power.Battery].Assembly 56 | } 57 | Catch 58 | { 59 | Write-Error "Unable to load the Windows.Devices.Power.Battery class" 60 | } 61 | 62 | Try{ 63 | $Report = [Windows.Devices.Power.Battery]::AggregateBattery.GetReport() 64 | } 65 | Catch{ 66 | Write-Error "Unable to retrieve Battery Report information" 67 | Break 68 | } 69 | 70 | If ($Report.Status -ne "NotPresent") 71 | { 72 | $pbmax = [convert]::ToDouble($Report.FullChargeCapacityInMilliwattHours) 73 | $pbvalue = [convert]::ToDouble($Report.RemainingCapacityInMilliwattHours) 74 | $Utilization = [int][math]::Round( (($pbvalue / $pbmax) *100)) 75 | $PowerOnlineStatus = (Get-CimInstance -ClassName batterystatus -Namespace root/WMI).PowerOnline 76 | 77 | # Check if at least one battery reports running on power 78 | If ($PowerOnlineStatus -contains "True") 79 | { 80 | $PowerOnline = $true 81 | } 82 | Else 83 | { 84 | $PowerOnline = $false 85 | } 86 | } 87 | Else 88 | { 89 | [int]$Utilization = 0 90 | $PowerOnline = "" 91 | } 92 | } 93 | 94 | 95 | Process 96 | { 97 | If ($Detail -eq $true) 98 | { 99 | $Properties = [ordered] @{ 100 | ChargeRateInMilliwatts = $Report.ChargeRateInMilliwatts 101 | DesignCapacityInMilliwattHours = $report.DesignCapacityInMilliwattHours 102 | FullChargeCapacityInMilliwattHours = $Report.FullChargeCapacityInMilliwattHours 103 | RemainingCapacityInMilliwattHours = $Report.RemainingCapacityInMilliwattHours 104 | Status = $Report.Status 105 | Utilization = $Utilization 106 | PowerOnline = $PowerOnline 107 | } 108 | $BatteryChargeStatus = (New-Object -TypeName PSObject -Property $Properties) 109 | } 110 | Elseif ($Detail -eq $false) 111 | { 112 | $Properties = [ordered] @{ 113 | Status = $Report.Status 114 | Utilization = $Utilization 115 | PowerOnline = $PowerOnline 116 | } 117 | $BatteryChargeStatus = (New-Object -TypeName PSObject -Property $Properties) 118 | } 119 | } 120 | End 121 | { 122 | $BatteryChargeStatus 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Windows10/Security/processmitigation.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | #http://sjc1-te-ftp.trendmicro.com/assets/wp/exploring-control-flow-guard-in-windows10.pdf 4 | 5 | 6 | #Find-Module -Name ProcessMitigations | Install-Module 7 | #https://docs.microsoft.com/en-us/windows/threat-protection/overview-of-threat-mitigations-in-windows-10 8 | # https://www.endgame.com/blog/technical-blog/disarming-control-flow-guard-using-advanced-code-reuse-attacks 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Windows10/Security/tpminfo.ps1: -------------------------------------------------------------------------------- 1 |  2 | # TPM Info 3 | Get-CimInstance -Namespace root/CIMV2/Security/MicrosoftTpm -ClassName Win32_Tpm 4 | 5 | Get-Tpm -------------------------------------------------------------------------------- /Windows10/Security/wdatpcheck.ps1: -------------------------------------------------------------------------------- 1 | 2 | 3 | # check wdatp config, event logs etc. 4 | Get-WinEvent -ProviderName "WDATPOnboarding" 5 | Get-WinEvent -Providername "Microsoft-Windows-Sense" 6 | Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection" 7 | Get-Service -Name DiagTrack 8 | Get-Service -Name Sense 9 | -------------------------------------------------------------------------------- /Windows10/get-osbuildinfo.ps1: -------------------------------------------------------------------------------- 1 | function Get-WinBuildInfo 2 | { 3 | <# 4 | .Synopsis 5 | Get-WinBuildInfo 6 | .DESCRIPTION 7 | Get-WinBuildInfo retrieves Windows 10 version, build and Insider information 8 | .EXAMPLE 9 | Get-WinBuildInfo 10 | .NOTES 11 | Sites with Windows build information: 12 | http://changewindows.org/platform/desktop 13 | https://buildfeed.net/ 14 | https://technet.microsoft.com/en-us/windows/release-info.aspx 15 | https://support.microsoft.com/en-us/help/12387/windows-10-update-history?ocid=client_wu 16 | #> 17 | 18 | [CmdletBinding()] 19 | Param 20 | ( 21 | ) 22 | 23 | Begin{ 24 | $osver = Get-ItemProperty -Path "HKLM:\software\microsoft\windows nt\currentversion" 25 | $insider = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsSelfHost\Applicability" 26 | 27 | 28 | switch($insider.Ring) 29 | { 30 | "WIS" {$InsiderLevel = "Slow"}; 31 | "WIF" {$InsiderLevel = "Fast"}; 32 | "RP" {$InsiderLevel = "Release Preview"}; 33 | Default {$InsiderLevel = "not found"} 34 | } 35 | } 36 | 37 | Process{ 38 | 39 | $props = [ordered]@{ 40 | "ProductName" = $osver.ProductName 41 | "CompositionEditionID" = $osver.CompositionEditionID 42 | "ReleaseID" = $osver.ReleaseID 43 | "BuildBranch" = $osver.BuildBranch 44 | "CurrentBuild" = $osver.CurrentBuild 45 | "CurrentBuildNumber" = $osver.CurrentBuildNumber 46 | "BuildLabEx" = $osver.BuildLabEx 47 | "CurrentVersion" = $osver.CurrentVersion 48 | "UBR" = $osver.UBR 49 | "CurrentMajorVersionNumber " = $osver.CurrentMajorVersionNumber 50 | "CurrentMinorVersionNumber" = $osver.CurrentMinorVersionNumber 51 | "PreviewBuildsEnabled" = $insider.EnablePreviewBuilds 52 | "InsiderLevel" = $InsiderLevel 53 | } 54 | $Results += @(New-Object pscustomobject -Property $props) 55 | } 56 | 57 | End 58 | { 59 | write-output $Results 60 | } 61 | } 62 | 63 | Get-WinBuildInfo 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /Windows10/readme.md: -------------------------------------------------------------------------------- 1 | # PowerShell Scripts for Windows 10 2 | 3 | ## Get-WinBuildInfo 4 | Get-WinBuildInfo retrieves Windows 10 version, build and Insider information 5 | 6 | ## BIOS_UEFI 7 | ### Get-BiosType 8 | Determines underlying firmware (BIOS) type and returns an integer indicating UEFI, Legacy BIOS or Unknown. 9 | 10 | 11 | ## Application compatibility 12 | ### Start-AppCert 13 | The start-appcert cmdlet launches the Microsoft Application Certification Toolkit and executes 14 | the tests for the specified application. 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /docker/ForensicSamples/Build/build.txt: -------------------------------------------------------------------------------- 1 | 2 | docker build -t="alextest01" . 3 | -------------------------------------------------------------------------------- /docker/ForensicSamples/Build/dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:14.04 2 | MAINTAINER Alex Verboon 3 | USER root 4 | RUN apt-get update && apt-get install -y \ 5 | git \ 6 | ruby \ 7 | ruby-dev \ 8 | bundler \ 9 | build-essential && \ 10 | rm -rf /var/lib/apt/lists/* 11 | 12 | RUN groupadd -r nonroot && \ 13 | useradd -r -g nonroot -d /home/nonroot -s /sbin/nologin -c "Nonroot User" nonroot && \ 14 | mkdir /home/nonroot && \ 15 | chown -R nonroot:nonroot /home/nonroot 16 | 17 | USER nonroot 18 | WORKDIR /home/nonroot 19 | 20 | RUN git clone https://github.com/volatilityfoundation/volatility.git 21 | 22 | USER root 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /docker/ForensicSamples/memory.txt: -------------------------------------------------------------------------------- 1 |  2 | 3 | # Launch Docker remnux with PeScanner Tool 4 | docker run --rm -it -v c:/temp/mem:/PEFiles remnux/volatility bash 5 | 6 | # https://github.com/hiddenillusion/AnalyzePE 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /docker/ForensicSamples/pescanner.txt: -------------------------------------------------------------------------------- 1 |  2 | 3 | # Launch Docker remnux with PeScanner Tool 4 | docker run --rm -it -v c:/temp/mem:/PEFiles remnux/pescanner bash 5 | 6 | # https://github.com/hiddenillusion/AnalyzePE 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /docker/One/app/app.txt: -------------------------------------------------------------------------------- 1 | This is the app -------------------------------------------------------------------------------- /docker/One/dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM ubuntu 3 | 4 | WORKDIR /app 5 | COPY /app/* /app 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /docker/Two/dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:8.2.0-alpine 2 | RUN mkdir -p /usr/src/app 3 | COPY ./app/* /usr/src/app/ 4 | WORKDIR /usr/src/app 5 | RUN npm install 6 | CMD node /usr/src/app/index.js -------------------------------------------------------------------------------- /docker/Two/howto.txt: -------------------------------------------------------------------------------- 1 | git clone https://github.com/Azure-Samples/aci-helloworld.git 2 | 3 | docker build ./aci-helloworld -t aci-tutorial-app 4 | docker run -d -p 8080:80 aci-tutorial-app 5 | 6 | docker run -d -p 8081:80 alex:web 7 | 8 | docker tag aci-tutorial-app alex:web 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /docker/build.ps1: -------------------------------------------------------------------------------- 1 | ############################### 2 | 3 | New-ContainerImage -Repository alex -Tag "six" -Verbose 4 | 5 | -------------------------------------------------------------------------------- /docker/iis/Untitled1.ps1: -------------------------------------------------------------------------------- 1 | #iis 2 | docker build -t iis-site . 3 | docker run -d -p 8000:8000 --name my-running-site iis-site -------------------------------------------------------------------------------- /docker/iis/dockerfile: -------------------------------------------------------------------------------- 1 | FROM microsoft/windowsservercore:1709 2 | 3 | RUN powershell -Command Add-WindowsFeature Web-Server 4 | 5 | ADD ServiceMonitor.exe /ServiceMonitor.exe 6 | 7 | EXPOSE 80 8 | 9 | ENTRYPOINT ["C:\\ServiceMonitor.exe", "w3svc"] -------------------------------------------------------------------------------- /docker/iis/iis.ps1: -------------------------------------------------------------------------------- 1 | #iis 2 | docker build -t iis-site . 3 | docker run -d -p 8000:8000 --name my-running-site iis-site -------------------------------------------------------------------------------- /docker/install-dockermodule.ps1: -------------------------------------------------------------------------------- 1 | # Install Docker PowerShell Module 2 | # https://github.com/Microsoft/Docker-PowerShell 3 | 4 | Register-PSRepository -Name DockerPS-Dev -SourceLocation https://ci.appveyor.com/nuget/docker-powershell-dev 5 | Install-Module Docker -Repository DockerPS-Dev 6 | Import-Module -FullyQualifiedName "C:\Program Files\WindowsPowerShell\Modules\Docker\0.1.0.111\Docker.psd1" 7 | 8 | 9 | #docker run -it -v c:\users\alexv\Documents\data:/data alex:sift 10 | 11 | # https://blog.codeship.com/docker-guis/ 12 | #docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock portainer/portainer 13 | 14 | -------------------------------------------------------------------------------- /docker/portainer.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock portainer/portainer 4 | 5 | -------------------------------------------------------------------------------- /en-US.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexverboon/posh/6d6f28883b14bf62e89932b1ab209cbfba6768b5/en-US.pdf -------------------------------------------------------------------------------- /kali/Get-KaliISO.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | $ImageName = "Download Kali Linux 64 Bit" 4 | $uri = "https://www.kali.org/downloads/" 5 | $kali = Invoke-WebRequest -uri $uri 6 | $IsoRef = $kali.links | select-object Title,href | where-object {$_.href -like "*iso*" -and $_.title -like "$ImageName"} 7 | $fileName = Split-Path $isoref.href -Leaf 8 | $contentinfo = Invoke-WebRequest -uri $IsoRef.href -Method Head 9 | 10 | Invoke-WebRequest -Uri $IsoRef.href -OutFile "c:\temp\$fileName" 11 | 12 | -------------------------------------------------------------------------------- /kali/Kali_Windows_Bash.txt: -------------------------------------------------------------------------------- 1 |  2 | https://www.kali.org/news/kali-linux-in-the-windows-app-store/ 3 | 4 | sudo apt-get update 5 | sudo apt-get dist-upgrade 6 | sudo apt-get clean 7 | 8 | # install metasploit 9 | sudo apt-get install metasploit-framework 10 | sudo apt-get install webshells 11 | 12 | -------------------------------------------------------------------------------- /psake/default.ps1: -------------------------------------------------------------------------------- 1 |  2 | properties { 3 | $version = $null 4 | } 5 | 6 | 7 | Task Lint -description 'Check scripts for style' { 8 | write-host "Run PS Script Analyzer" 9 | } 10 | 11 | Task Test -description 'Run unit tests' { 12 | Write-Host "Run Pester" 13 | } 14 | 15 | Task Package -description 'Package the module' { 16 | write-host "Package the module" 17 | write-host "Package Module $version" 18 | } 19 | 20 | Task Deploy -description 'Deploy to the Gallery' { 21 | write-host "Deploy the package" 22 | } 23 | Task Default -depends Lint,Test 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /psake/learn.ps1: -------------------------------------------------------------------------------- 1 |  2 | 3 | Invoke-psake -properties @{"version"="1.0"} Package -------------------------------------------------------------------------------- /test/runme.ps1: -------------------------------------------------------------------------------- 1 | Function Runme{ 2 | 3 | Param( 4 | $Param1 5 | ) 6 | 7 | Write-host "I was just downloaded" 8 | write-host "And executed with $Param1" 9 | pause 10 | } 11 | --------------------------------------------------------------------------------