├── 001-Start01.zip ├── ActiveDirectory └── Show-ADGroupMemberTreeViewDiagramHierarchyGUI │ ├── Diagram.html │ ├── Extras │ ├── Diagram.eps │ ├── EPS │ │ └── 1.0.0 │ │ │ ├── EPS.psd1 │ │ │ ├── EPS.psm1 │ │ │ ├── Each.ps1 │ │ │ ├── Get-OrElse.ps1 │ │ │ ├── Invoke-EpsTemplate.ps1 │ │ │ ├── New-EpsTemplateScript.ps1 │ │ │ └── PSGetModuleInfo.xml │ ├── diagram.mmd │ ├── group.gif │ ├── group.png │ ├── mermaid.min.js │ ├── rawdiagram.mmd │ └── script.js │ └── Get-ADGroupTree.ps1 ├── Automate_Chrome_Browser_using_PowerShell_Selenium.zip ├── Azure management with PowerShell and Github Actions.zip ├── Azure ├── AzVMSecurityConfig.ps1 ├── Az_vNet │ ├── New-AzSubnetInvNet.ps1 │ └── New-AzvNetWithSubnet.ps1 ├── Azure_API_Example.ps1 ├── Azure_API_Example_With_Credentials.zip ├── Change-AzVMSize.ps1 ├── Configure-CertificateBasedAzureLogin.ps1 ├── Export-AzKeyVaultCertificate.ps1 ├── Find-AzureBlobFile.ps1 ├── Generate-AzKeyVaultCertificate.ps1 ├── Get-AzKeyVaultSecret.ps1 ├── Get-AzKeyVaultSecretValue.ps1 ├── Get-AzVMBackupInformation.ps1 ├── Get-AzureReservationsVM.ps1 ├── Get-AzureVirtualNetworkInfo.ps1 ├── Get-ManagedIdentityKeyVaultSecret.ps1 ├── New-AzADAppRegistrations ├── New-AzAutomationAccountRunAs.ps1 ├── New-CliAzKeyVault.ps1 ├── New-PsAzKeyVault.ps1 ├── resource_group_azure_ARM_template_PowerShell.zip ├── vCenter_Profiles.ps1 └── vCenter_ProfilesGUI.ps1 ├── Azure_Bicep_Subscription_Usage_Quota_Rule.zip ├── Azure_Rest_API_PowerShell ├── PowerShellAzModuleAzureRestAPI.ps1 └── PowerShellAzureRestApiExample.ps1 ├── CPU_Quota_Alert_Azure_ARM_templates.zip ├── EncryptDecrypt_PasswordTool.zip ├── ExchangeOnline_Office365 └── Add-DistributionGroupEmailAddresses.ps1 ├── Generate-XMLWithNetObject1.ps1 ├── Generate_New_GUID.ps1 ├── Get-IDRACPowerState.ps1 ├── Get-UpdateReport.zip ├── HPE_ILO └── SNMP │ └── Set-HPEILOSNMPConfiguration.ps1 ├── HTML PHP Linux Server Reboot Tool with Authorization.zip ├── HTML ├── HTML_Reporting01 │ ├── Demo-Interactive_WebPage_With_PowerShell_Data.zip │ ├── ServerAssetInventory.ps1 │ ├── css │ │ └── styles.css │ ├── data.js │ ├── images │ │ └── server_inventory_logo.png │ ├── index.html │ ├── js │ │ └── javascript.js │ └── serverInventory02Test.ps1 └── Web_Based_Live_Ping_Monitor_Dashboard │ └── live4.1.zip ├── HappyNewYear.ps1 ├── IIS configuration Script.txt ├── Install-KubeCTL.ps1 ├── Karpekar V1.ps1 ├── Karpekar's Constant.ps1 ├── Live_HTML_Rack_Cabinet_Maker.zip ├── Live_HTML_Rack_Cabinet_Maker ├── FetchRackInfo.ps1 ├── RackServers.csv ├── dbase │ ├── serverData.json │ └── serverData.json.bak ├── img │ ├── bladeserver.png │ ├── circle │ │ ├── extra │ │ │ ├── Black.png │ │ │ ├── Blue.png │ │ │ ├── BlueSky.png │ │ │ ├── Brown.png │ │ │ ├── Cyan.png │ │ │ ├── Fuchsia.png │ │ │ ├── Green.png │ │ │ ├── GreenForest.png │ │ │ ├── GreenYellow.png │ │ │ ├── Lime.png │ │ │ ├── Orange.png │ │ │ ├── Pink.png │ │ │ ├── Purple.png │ │ │ ├── Red.png │ │ │ ├── Tomato.png │ │ │ ├── Turquoise.png │ │ │ ├── Violet.png │ │ │ ├── White.png │ │ │ └── Yellow.png │ │ ├── off.png │ │ ├── on.png │ │ └── unknown.png │ ├── empty.png │ ├── firewall.png │ ├── information.png │ ├── kvmswitch.png │ ├── networkswitch.png │ ├── patchpanel.png │ ├── rack_cabinet.png │ ├── server.png │ ├── storageserver.png │ └── ups.png ├── index.html ├── js │ └── script.js └── styles │ └── style.css ├── Manage-EsxiUserAccount.ps1 ├── Mouse_Cursor_Tracker.ps1 ├── MyDiskReport.ps1 ├── New MahApp Metro Theme.zip ├── New-DnsRecords.ps1 ├── PHP_ldap_ssh2_connect.zip ├── PHP_reboot_linux_PowerShell.zip ├── PowerCLI └── ESXi_TCP_IP_Configuration │ ├── ESXi_TCP_IP_Configuration.ps1 │ ├── Gather_Information │ └── Get-VirtualDistributedSwitchInfo.ps1 │ └── MainWindow.xaml ├── PowerShell GUI Hardware Information.zip ├── PowerShell Wpf databinding DataTemplate DataContext ├── PowerShell_Simple_DataBinding.zip ├── PowerShell_Simple_DataBinding │ ├── Simple_Binding_.netObject.ps1 │ └── Simple_binding.ps1 ├── PowerShell_WPF_Control_To_Control_Binding.zip ├── PowerShell_WPF_Control_To_Control_Binding │ ├── Control_to_Control_Binding.netObject.ps1 │ └── Control_to_Control_Binding.ps1 ├── PowerShell_WPF_Datagrid_binding │ └── Powershell_WPF_Datagrid_Binding.ps1 └── PowerShell_WPF_MultiBinding_DataContext │ └── Powershell_WPF_DataContext_DataTemplate.ps1 ├── PowerShell_PHP_Project.zip ├── README.md ├── Selenium_Automation_Office.zip ├── Send-Email ├── Send-Email-01.ps1 └── Send-Email-02.ps1 ├── Send-PasswordExpiryNotification.ps1 ├── Set-ExternalContentPowerShellWebServer.zip ├── Set-Log.ps1 ├── VMware.PowerCLI └── Show-VMDiskRelationshipMapping │ ├── DiskInfo.csv │ ├── DiskMapping.html │ ├── Show-VMDiskRelationshipMapping.ps1 │ ├── Show-VMDiskRelationshipMapping.zip │ └── _extras │ ├── Diagram.eps │ ├── EPS │ └── 1.0.0 │ │ ├── EPS.psd1 │ │ ├── EPS.psm1 │ │ ├── Each.ps1 │ │ ├── Get-OrElse.ps1 │ │ ├── Invoke-EpsTemplate.ps1 │ │ ├── New-EpsTemplateScript.ps1 │ │ └── PSGetModuleInfo.xml │ ├── VMDetailsGUI.ps1 │ ├── mermaid.min.js │ ├── script.js │ └── styles.css ├── basic_webserver_httplistener.ps1 ├── convert to xml examples.ps1 ├── encode-decode-base64.ps1 ├── encode-decode-weburl.ps1 ├── nutanix_ahv.ps1 ├── parameters_pipeline.yaml └── unattend.xaml_sysprep.zip /001-Start01.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/001-Start01.zip -------------------------------------------------------------------------------- /ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Diagram.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 | 7 |.*?)(?[-=])?(?(?[ \t]*\r?\n)?")
10 | $StringBuilder = New-Object -TypeName "System.Text.StringBuilder"
11 |
12 | function Add-Prolog {
13 | [void]$StringBuilder.`
14 | Append("`$sb = New-Object -TypeName 'System.Text.StringBuilder'`n").`
15 | Append("[void]`$(`n")
16 | }
17 |
18 | function Add-String {
19 | Param([String]$Value)
20 |
21 | if ($Value) {
22 | $Value = $Value -replace '([`"$])', '`$1'
23 | [void]$StringBuilder.Append(";`$sb.Append(`"").Append($Value).Append("`");")
24 | }
25 | }
26 |
27 | function Add-LiteralString {
28 | Param([String[]]$Values)
29 |
30 | foreach ($Value in $Values) {
31 | [void]$StringBuilder.Append($Value)
32 | }
33 | }
34 |
35 | function Add-Expression {
36 | Param([String]$Value)
37 |
38 | [void]$StringBuilder.`
39 | Append("`$sb.Append(`"`$(").`
40 | Append($Value.Replace('""', '`"`"')).`
41 | Append(")`");")
42 | }
43 |
44 | function Add-Code {
45 | Param([String]$Value)
46 |
47 | [void]$StringBuilder.Append($Value)
48 | }
49 |
50 | function Add-Epilog {
51 | [void]$StringBuilder.Append("`n)`n`$sb.ToString()")
52 | }
53 |
54 | Add-Prolog
55 | $Pattern.Matches($Template) | ForEach-Object {
56 | $match = $_
57 | $contentLength = $match.Index - $position
58 | $content = $Template.Substring($position, $contentLength)
59 | $position = $match.Index + $match.Length
60 | $lit = $match.Groups["lit"]
61 |
62 | if ($lit.Success) {
63 | if ($contentLength -ne 0) {
64 | Add-String $content
65 | }
66 | switch ($lit.Value) {
67 | "<%%" {
68 | Add-String "<%"
69 | }
70 | "%%>" {
71 | Add-String "%>"
72 | }
73 | }
74 | } else {
75 | $ind = $match.Groups["ind"].Value
76 | $code = $match.Groups["code"].Value
77 | $tail = $match.Groups["tailch"].Value
78 | $rspace = $match.Groups["rspace"].Value
79 |
80 | if (($ind -ne '-') -and ($contentLength -ne 0)) {
81 | Add-String $content
82 | } else {
83 | Add-Code ";"
84 | }
85 | switch ($ind) {
86 | '=' {
87 | Add-Expression $code.Trim()
88 | }
89 | '-' {
90 | Add-String ($content -replace '(?smi)([\n\r]+|\A)[ \t]+\z', '$1')
91 | Add-Code $code.Trim()
92 | }
93 | '' {
94 | Add-Code $code.Trim()
95 | }
96 | '#' { # Do nothing
97 | }
98 | }
99 | if (($ind -ne '%') -and (($tail -ne '-') -or ($rspace -match '^[^\r\n]'))) {
100 | Add-String $rspace
101 | } else {
102 | Add-Code ";"
103 | }
104 | }
105 | }
106 | if ($position -eq 0) {
107 | Add-String $Template
108 | } elseif ($position -lt $Template.Length) {
109 | Add-String $Template.Substring($position, $Template.Length - $position)
110 | }
111 | Add-Epilog
112 |
113 | [ScriptBlock]::Create($StringBuilder.ToString())
114 | }
115 |
--------------------------------------------------------------------------------
/ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Extras/diagram.mmd:
--------------------------------------------------------------------------------
1 | flowchart TD;
2 | Group1(Group1) --> Group2(Group2);
3 | Group1(Group1) --> Group3(Group3);
4 | Group1(Group1) --> user10(user10); style Group1 fill:#CC5500,color:white;
5 | Group1(Group1) --> user11(user11);
6 | Group15(Group15) --> user12(user12);
7 | Group15(Group15) --> user13(user13);
8 | Group15(Group15) --> user14(user14);
9 | Group2(Group2) --> Group15(Group15);
10 | Group2(Group2) --> user10(user10);
11 | Group2(Group2) --> user11(user11);
12 | Group3(Group3) --> Group4(Group4);
13 | Group3(Group3) --> Group5(Group5);
14 | Group4(Group4) --> Group6(Group6);
15 | Group4(Group4) --> Group7(Group7);
16 | Group4(Group4) --> user7(user7);
17 | Group4(Group4) --> user8(user8);
18 | Group4(Group4) --> user9(user9);
19 | Group6(Group6) --> Group14(Group14);
20 | Group6(Group6) --> Group15(Group15);
21 | Group6(Group6) --> user19(user19);
22 | Group6(Group6) --> user20(user20);
23 |
--------------------------------------------------------------------------------
/ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Extras/group.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Extras/group.gif
--------------------------------------------------------------------------------
/ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Extras/group.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Extras/group.png
--------------------------------------------------------------------------------
/ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Extras/rawdiagram.mmd:
--------------------------------------------------------------------------------
1 | Group1(Group1) --> user10(user10);
2 | Group1(Group1) --> user11(user11);
3 | Group1(Group1) --> Group2(Group2);
4 | Group1(Group1) --> Group3(Group3);
5 | Group3(Group3) --> Group4(Group4);
6 | Group3(Group3) --> Group5(Group5);
7 | Group4(Group4) --> user7(user7);
8 | Group4(Group4) --> user8(user8);
9 | Group4(Group4) --> user9(user9);
10 | Group4(Group4) --> Group6(Group6);
11 | Group4(Group4) --> Group7(Group7);
12 | Group6(Group6) --> user19(user19);
13 | Group6(Group6) --> user20(user20);
14 | Group6(Group6) --> Group14(Group14);
15 | Group6(Group6) --> Group15(Group15);
16 | Group15(Group15) --> user12(user12);
17 | Group15(Group15) --> user13(user13);
18 | Group15(Group15) --> user14(user14);
19 | Group2(Group2) --> user10(user10);
20 | Group2(Group2) --> user11(user11);
21 | Group2(Group2) --> Group15(Group15);
22 | Group15(Group15) --> user12(user12);
23 | Group15(Group15) --> user13(user13);
24 | Group15(Group15) --> user14(user14);
25 |
--------------------------------------------------------------------------------
/ActiveDirectory/Show-ADGroupMemberTreeViewDiagramHierarchyGUI/Extras/script.js:
--------------------------------------------------------------------------------
1 | const config = {
2 | startOnLoad: true,
3 | flowchart: { useMaxWidth: true, htmlLabels: true, curve: 'cardinal' },
4 | securityLevel: 'loose',
5 | };
6 |
7 | document.addEventListener('DOMContentLoaded', function() {
8 | mermaid.initialize(config);
9 | });
10 |
11 | function autoRefresh() {
12 | window.location = window.location.href;
13 | }
14 | setInterval('autoRefresh()', 30000);
--------------------------------------------------------------------------------
/Automate_Chrome_Browser_using_PowerShell_Selenium.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/Automate_Chrome_Browser_using_PowerShell_Selenium.zip
--------------------------------------------------------------------------------
/Azure management with PowerShell and Github Actions.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/Azure management with PowerShell and Github Actions.zip
--------------------------------------------------------------------------------
/Azure/AzVMSecurityConfig.ps1:
--------------------------------------------------------------------------------
1 | #Written by vJanvi May 2021
2 | #Azure Automation Accounts DSC (Desired State Configuration)
3 |
4 | $password = "Computer@1" | ConvertTo-SecureString -asPlainText -Force
5 | $username = "vJanvi"
6 | [PSCredential]$credential = New-Object System.Management.Automation.PSCredential($username,$password)
7 |
8 | $configurationData = @{
9 | AllNodes = @(
10 | @{
11 | NodeName = '*'
12 | PSDscAllowPlainTextPassword = $True
13 | }
14 | @{
15 | NodeName = "localhost"
16 | }
17 | )
18 | }
19 |
20 | Configuration AzVMSecurityConfig
21 | {
22 | [CmdletBinding()]
23 | param (
24 | [Parameter()]
25 | [string]$ComputerName = 'localhost'
26 | )
27 | Import-DscResource –ModuleName 'PSDesiredStateConfiguration'
28 | Node $ComputerName
29 | {
30 | File NewDirectory
31 | {
32 | Ensure = "Present"
33 | Type = "Directory"
34 | DestinationPath = "C:\Temp"
35 | Force = $true
36 | }
37 |
38 | Environment EnvVarAddPath
39 | {
40 | Ensure = "Present"
41 | Name = "Path"
42 | Path = $true
43 | Value = ";C:\temp"
44 | DependsOn = "[File]NewDirectory"
45 | }
46 |
47 | User NewUser
48 | {
49 | Ensure = "Present"
50 | UserName = "vJanvi"
51 | Description = "Second Admin"
52 | PasswordNeverExpires = $true
53 | Password = $credential
54 | }
55 |
56 | Group AddUserToGroup
57 | {
58 | Ensure = "Present"
59 | GroupName = "Remote Desktop Users"
60 | Members = "vJanvi"
61 | DependsOn = "[User]NewUser"
62 | }
63 |
64 | $features = @()
65 | $features += [pscustomobject]@{ConfigName = "TelnetClient"; Name = "Telnet-Client"; Ensure = "Present"}
66 | $features += [pscustomobject]@{ConfigName = "FSSMB1"; Name = "FS-SMB1"; Ensure = "Absent"}
67 | foreach ($feature in $features)
68 | {
69 | WindowsFeature $feature.ConfigName
70 | {
71 | Ensure = $feature.Ensure
72 | Name = $feature.Name
73 | }
74 | }
75 | }
76 | }
77 |
78 | AzVMSecurityConfig -ConfigurationData $configurationData
79 |
80 | #Start-DscConfiguration -Wait -Path AzVMSecurityConfig -Verbose -Force
--------------------------------------------------------------------------------
/Azure/Az_vNet/New-AzSubnetInvNet.ps1:
--------------------------------------------------------------------------------
1 | $vNetName = 'global_vnet_eastus'
2 | $resourceGroupName = 'vcloud-lab.com'
3 | $location = 'eastus'
4 | $AddressPrefix = @('10.10.0.0/16')
5 | $subnet01Name = 'prod01-10.10.1.x'
6 | $subnet01AddressPrefix = '10.10.1.0/24'
7 |
8 | #Create new Azure Virtual Network without subnet
9 | New-AzVirtualNetwork -Name $vNetName -ResourceGroupName $resourceGroupName -Location $location -AddressPrefix $AddressPrefix
10 |
11 | #Get existing Azure Virtual Network information
12 | $azvNet = Get-AzVirtualNetwork -Name $vNetName -ResourceGroupName $resourceGroupName
13 | Add-AzVirtualNetworkSubnetConfig -Name $subnet01Name -AddressPrefix $subnet01AddressPrefix -VirtualNetwork $azvNet
14 |
15 | #Make changes to vNet
16 | $azvNet | Set-AzVirtualNetwork
--------------------------------------------------------------------------------
/Azure/Az_vNet/New-AzvNetWithSubnet.ps1:
--------------------------------------------------------------------------------
1 | #Connect Azure with PowerShell
2 | Connect-AzAccount
3 |
4 | $vNetName = 'global_vnet_eastus'
5 | $resourceGroupName = 'vcloud-lab.com'
6 | $location = 'eastus'
7 | $AddressPrefix = @('10.10.0.0/16')
8 | $subnet01Name = 'prod02-10.10.1.x'
9 | $subnet01AddressPrefix = '10.10.1.0/24'
10 |
11 | #Create new Azure Virtual Network Subnet configuration
12 | $subnet01 = New-AzVirtualNetworkSubnetConfig -Name $subnet01Name -AddressPrefix $subnet01AddressPrefix
13 |
14 | #Create new Azure Virtual Network with above subnet configuration
15 | New-AzVirtualNetwork -Name $vNetName -ResourceGroupName $resourceGroupName -Location $location -AddressPrefix $AddressPrefix -Subnet $subnet01
16 |
17 | #######################################
18 | #Remove Azure Virtual Network
19 | Remove-AzVirtualNetwork -Name $vNetName -ResourceGroupName $resourceGroupName
20 |
--------------------------------------------------------------------------------
/Azure/Azure_API_Example.ps1:
--------------------------------------------------------------------------------
1 | #Url: http://vcloud-lab.com
2 | #Date: 6 may 2019
3 | #Author: Janvi
4 |
5 | #Microsoft Azure Rest API authentication
6 | #https://docs.microsoft.com/en-us/rest/api/azure/
7 | $subscriptionId = '9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
8 | $tenantId = '3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
9 | $applicationId = '2e4736e8-8e38-4122-92fe-290933b172f1'
10 | $secret='.9Dyd2U3yM2YD8Wn58XG~bX.z-V.PwN.M0'
11 |
12 | $param = @{
13 | #Uri = "https://login.microsoftonline.com/$tenantId/oauth2/token?api-version=1.0";
14 | Uri = "https://login.microsoftonline.com/$tenantId/oauth2/token?api-version=2020-06-01";
15 | Method = 'Post';
16 | Body = @{
17 | grant_type = 'client_credentials';
18 | resource = 'https://management.core.windows.net/';
19 | client_id = $applicationId;
20 | client_secret = $secret
21 | }
22 | }
23 |
24 | $result = Invoke-RestMethod @param
25 | $token = $result.access_token
26 |
27 | #Get the list of Resource Groups
28 | #https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/list
29 | $param_RGList = @{
30 | Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups?api-version=2020-06-01"
31 | ContentType = 'application/json'
32 | Method = 'GET'
33 | headers = @{
34 | authorization = "Bearer $token"
35 | host = 'management.azure.com'
36 | }
37 | }
38 |
39 | $rgList = Invoke-RestMethod @param_RGList
40 | $rgList.value | Select-Object name, location, id
41 |
42 | #Create or update subscriptionId and resource group name
43 | #https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/createorupdate
44 | $newResourceGroupName = 'TestResourceGroup'
45 |
46 | $param_NewResourceGroup = @{
47 | Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${newResourceGroupName}?api-version=2020-06-01"
48 | ContentType = "application/json"
49 | Method = 'PUT'
50 | headers=@{
51 | authorization="Bearer $token"
52 | host = 'management.azure.com'
53 | }
54 | body = '
55 | {
56 | "location": "eastus",
57 | "tags": {
58 | "owner": "http://vcloud-lab.com"
59 | }
60 | }
61 | '
62 | }
63 |
64 | Invoke-RestMethod @param_NewResourceGroup
65 |
66 | #Get Resource Group Information
67 | #https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/get
68 | $param_RGInfo = @{
69 | Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($newResourceGroupName)?api-version=2020-06-01"
70 | ContentType = 'application/json'
71 | Method = 'GET'
72 | headers = @{
73 | authorization = "Bearer $token"
74 | host = 'management.azure.com'
75 | }
76 | }
77 |
78 | $rgInfo = Invoke-RestMethod @param_RGInfo
79 | $rgInfo | Select-Object name, location, tags, id
80 |
81 | #Delete Resource Group Information
82 | #https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/delete
83 | $param_DeleteResourceGroup = @{
84 | Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${newResourceGroupName}?api-version=2020-06-01"
85 | ContentType = "application/json"
86 | Method = 'Delete'
87 | headers=@{
88 | authorization = "Bearer $token"
89 | host = 'management.azure.com'
90 | }
91 | }
92 | Invoke-RestMethod @param_DeleteResourceGroup
--------------------------------------------------------------------------------
/Azure/Azure_API_Example_With_Credentials.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/Azure/Azure_API_Example_With_Credentials.zip
--------------------------------------------------------------------------------
/Azure/Change-AzVMSize.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .SYNOPSIS
3 | Stops an Azure Virtual Machine, changes its size, and then starts it again.
4 |
5 | .DESCRIPTION
6 | This script automates the process of resizing an Azure Virtual Machine.
7 | It first retrieves the specified VM, gracefully stops it (which is required
8 | for most VM size changes), updates its hardware profile with the new VM size,
9 | and then starts the VM back up.
10 | Error handling is included to provide informative messages if operations fail.
11 |
12 | .PARAMETER VmName
13 | The name of the Azure Virtual Machine to be resized.
14 |
15 | .PARAMETER ResourceGroupName
16 | The name of the Azure Resource Group where the Virtual Machine resides.
17 |
18 | .PARAMETER NewVmSize
19 | The new Azure VM size (e.g., 'Standard_DS2_v2', 'Standard_D4s_v3').
20 | Ensure the new size is compatible with the existing VM configuration
21 | (e.g., supported disk types, available in the region).
22 |
23 | .EXAMPLE
24 | # Resize a VM named 'MyWebAppVM' in 'ProductionRG' to 'Standard_D4s_v3'
25 | .\Resize-AzVM.ps1 -VmName "MyWebAppVM" -ResourceGroupName "ProductionRG" -NewVmSize "Standard_D4s_v3"
26 |
27 | .EXAMPLE
28 | # Resize a VM and provide credentials if not already logged in (advanced)
29 | # Connect-AzAccount # Ensure you are logged into Azure
30 | # Get-AzSubscription | Out-GridView -PassThru | Select-AzSubscription # Select correct subscription
31 | # .\Resize-AzVM.ps1 -VmName "AppServer" -ResourceGroupName "DevServers" -NewVmSize "Standard_B2s"
32 |
33 | .NOTES
34 | - Ensure you are logged into your Azure account via `Connect-AzAccount` before running this script.
35 | - Ensure you have selected the correct Azure subscription using `Select-AzSubscription` if you have multiple.
36 | - Not all VM sizes are available in all regions or compatible with all disk types.
37 | You can use `Get-AzVMSize -Location ` to see available sizes.
38 | - Stopping the VM will incur downtime. Plan accordingly.
39 | - The original script had a commented-out line for tagging. You can uncomment and
40 | customize this line to automatically tag the VM after a size change if needed:
41 | `Get-AzResource -ResourceGroupName $ResourceGroupName -Name $VmName -ResourceType 'Microsoft.Compute/virtualMachines' | Set-AzResource -Tag @{ 'VMSizeChange' = 'True' } -Force`
42 | - Created by Janvi on 2024-10-01.
43 | - link: https://vcloud-lab.com
44 | - This script is provided as-is without warranty of any kind.
45 | #>
46 | param(
47 | [Parameter(Mandatory=$true)]
48 | [string]$VmName = 'test',
49 |
50 | [Parameter(Mandatory=$true)]
51 | [string]$ResourceGroupName = 'test',
52 |
53 | [Parameter(Mandatory=$true)]
54 | [string]$NewVmSize = 'Standard_DS1_v2' #'Standard_DS2_v2'
55 | )
56 |
57 | Write-Host "--- Azure VM Resizing Script ---" -ForegroundColor Cyan
58 |
59 | # --- Step 1: Validate Azure Connection ---
60 | try {
61 | if (-not (Get-Module -Name Az.Compute -ListAvailable)) {
62 | Write-Warning "Az.Compute module not found. Please install Azure PowerShell modules: Install-Module -Name Az -Scope CurrentUser"
63 | }
64 | $azContext = Get-AzContext -ErrorAction SilentlyContinue
65 | if (-not $azContext) {
66 | Write-Error "Not connected to Azure. Please run 'Connect-AzAccount' and 'Select-AzSubscription' if needed."
67 | }
68 | Write-Host "Connected to Azure subscription: $($azContext.Subscription.Name)" -ForegroundColor Green
69 | }
70 | catch {
71 | Write-Error "Azure connection check failed: $($_.Exception.Message)"
72 | }
73 |
74 | # --- Step 2: Get the Virtual Machine ---
75 | Write-Host "Retrieving VM '$VmName' in Resource Group '$ResourceGroupName'..." -ForegroundColor Cyan
76 | try {
77 | $vm = Get-AzVM -Name $VmName -ResourceGroupName $ResourceGroupName -ErrorAction Stop
78 | Write-Host "VM '$VmName' found. Current size: $($vm.HardwareProfile.VmSize)" -ForegroundColor Green
79 | }
80 | catch {
81 | Write-Error "Failed to retrieve VM '$VmName'. Error: $($_.Exception.Message)"
82 | Write-Error "Please ensure VM name and Resource Group are correct."
83 | }
84 |
85 | # --- Step 3: Stop the Virtual Machine ---
86 | Write-Host "Stopping VM '$VmName'..." -ForegroundColor Yellow
87 | try {
88 | $vm | Stop-AzVM -Force -ErrorAction Stop | Out-Null # -Force bypasses confirmation
89 | Write-Host "VM '$VmName' stopped successfully." -ForegroundColor Green
90 | }
91 | catch {
92 | Write-Error "Failed to stop VM '$VmName'. Error: $($_.Exception.Message)"
93 | }
94 |
95 | # --- Step 4: Update VM Size ---
96 | Write-Host "Attempting to change VM size from '$($vm.HardwareProfile.VmSize)' to '$NewVmSize'..." -ForegroundColor Cyan
97 | try {
98 | $vm.HardwareProfile.VmSize = $NewVmSize
99 | $vm | Update-AzVM -ErrorAction Stop | Out-Null
100 | Write-Host "VM '$VmName' size update initiated successfully." -ForegroundColor Green
101 | }
102 | catch {
103 | Write-Error "Failed to update VM size for '$VmName'. Error: $($_.Exception.Message)"
104 | Write-Error "Common reasons: Incompatible VM size, size not available in region, or resource locks."
105 | }
106 |
107 | # --- Step 5: Verify New VM Size (Optional, but good practice) ---
108 | Write-Host "Verifying new VM size..." -ForegroundColor Cyan
109 | try {
110 | # Re-retrieve VM object to get the latest properties
111 | $vm = Get-AzVM -Name $VmName -ResourceGroupName $ResourceGroupName -ErrorAction Stop
112 | Write-Host "VM '$VmName' new size: $($vm.HardwareProfile.VmSize)" -ForegroundColor Green
113 | }
114 | catch {
115 | Write-Warning "Could not re-retrieve VM properties to verify size. Error: $($_.Exception.Message)"
116 | }
117 |
118 | # --- Step 6: Start the Virtual Machine ---
119 | Write-Host "Starting VM '$VmName'..." -ForegroundColor Yellow
120 | try {
121 | $vm | Start-AzVM -ErrorAction Stop | Out-Null
122 | Write-Host "VM '$VmName' started successfully." -ForegroundColor Green
123 | }
124 | catch {
125 | Write-Error "Failed to start VM '$VmName'. Error: $($_.Exception.Message)"
126 | }
127 |
128 | Write-Host "--- VM Resizing Script Completed ---" -ForegroundColor Green
--------------------------------------------------------------------------------
/Azure/Configure-CertificateBasedAzureLogin.ps1:
--------------------------------------------------------------------------------
1 | #generate a self singed SSL certififate
2 | New-SelfSignedCertificate -CertStoreLocation cert:\CurrentUser\my -Subject CN=CertLogin -KeySpec KeyExchange -FriendlyName CertLogin
3 |
4 | #Get certifiate thumbprint
5 | $certificate = Get-ChildItem Cert:\CurrentUser\my | Where-Object {$_.Subject -eq 'CN=CertLogin'}
6 | $thumbprint = $certificate.Thumbprint
7 | $thumbprint
8 |
9 | #Download/Export certififate
10 | $certificate = Get-ChildItem -Path "cert:\CurrentUser\My\$thumbprint"
11 | Export-Certificate -Cert $certificate -FilePath c:\temp\loggingcert.cer
12 |
13 | #App registeration information
14 | $applicationId = '61e492e8-cbc2-48e4-880a-ec39187567a5'
15 | $subscriptionId = '9e22fba3-00a9-447c-b954-a26fec38e029'
16 | $tenantId = '3b80e97b-2973-44fb-8192-c18e52ddcf98'
17 |
18 |
19 | #Login with Certificate
20 | Connect-AzAccount -ServicePrincipal -CertificateThumbprint $thumbprint -Tenant $tenantId -ApplicationId $applicationId -SubscriptionId $subscriptionId
21 |
22 | Get-AzResourcegroup
23 |
24 | Get-AzKeyVaultSecret -VaultName vcloudkeyvault -Name test -AsPlainText
25 | #$secret = Get-AzKeyVaultSecret -VaultName vcloudkeyvault -Name test
26 | #$key = ConvertFrom-SecureString $secret.SecretValue -AsPlainText
27 | #$key
--------------------------------------------------------------------------------
/Azure/Export-AzKeyVaultCertificate.ps1:
--------------------------------------------------------------------------------
1 | [CmdletBinding(SupportsShouldProcess=$True,
2 | ConfirmImpact='Medium',
3 | HelpURI='http://vcloud-lab.com',
4 | DefaultParameterSetName = 'pfx'
5 | )]
6 |
7 | <#
8 | .SYNOPSIS
9 | Export Azure key vault certificates to file.
10 |
11 | .DESCRIPTION
12 | Download/Export certificate files from Azure Key vault, it downloads certificate in cer or pfx extension format
13 |
14 | .PARAMETER Path
15 | Speciry Directory path to donwload/export Azure Key Vault certificate files.
16 |
17 | .PARAMETER CertificateName
18 | Specify Name of the Azure KeyVault Certificate.
19 |
20 | .PARAMETER KeyVaultName
21 | Specify Name of the Azure Key Vault Where certificate is stored.
22 |
23 | .PARAMETER Pfx
24 | This parameter exports certificate file in PFX extension format.
25 |
26 | .PARAMETER Cer
27 | This parameter exports certificate file in CER extenstion format.
28 |
29 | .PARAMETER PfxCertPassword
30 | If you are using PFX to export certificate, mention Password with this parameter.
31 |
32 | .INPUTS
33 | None. Export Azure key vault certificates to file.
34 |
35 | .OUTPUTS
36 | Export Azure key vault certificates to file in given path.
37 |
38 | .EXAMPLE
39 | PS> .\Export-AzKeyVaultCertificate.ps1 -Path C:\temp\certs -CertificateName vcloud-lab-Automation-Account-Ps -KeyVaultName vcloudvault -PfxCertPassword 123456 -Pfx
40 | This example to Export certificate in Pfx file format
41 |
42 | .EXAMPLE
43 | PS> .\Export-AzKeyVaultCertificate.ps1 -Path C:\temp\certs -CertificateName vcloud-lab-Automation-Account-Ps -KeyVaultName vcloudvault -Cer
44 | This example to Export certificate in Cer file format
45 |
46 | .LINK
47 | Online version: http://vcloud-lab.com
48 | http://vcloud-lab.com/entries/microsoft-azure/-create-azure-key-vault-certificates-on-azure-portal-and-powershell
49 |
50 | .LINK
51 | Export-AzKeyVaultCertificate.ps1
52 | #>
53 | Param
54 | (
55 | [parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'cer' )]
56 | [parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'pfx' )]
57 | [alias('Directory')]
58 | [string]$Path = 'C:\Temp\certs',
59 | [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'cer' )]
60 | [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'pfx' )]
61 | [alias('Certificate')]
62 | [string]$CertificateName = 'vcloud-lab-Automation-Account-Ps',
63 | [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'cer' )]
64 | [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'pfx' )]
65 | [string]$KeyVaultName = 'vcloudvault',
66 | [parameter(Position=2, ParameterSetName = 'pfx', Mandatory=$true)]
67 | [switch]$Pfx,
68 | [parameter(Position=3, ParameterSetName = 'pfx')]
69 | [string]$PfxCertPassword = '123456',
70 | [parameter(Position=2, ParameterSetName = 'cer', Mandatory=$true)]
71 | [switch]$Cer
72 | ) #Param
73 | begin
74 | {
75 | $testFolderPath = Test-Path $Path
76 | if ($testFolderPath -eq $false)
77 | {
78 | New-Item -Path $Path -ItemType Directory -Force | Out-Null
79 | }
80 | $certFolderPath = $Path
81 |
82 | #Verify Azure Key Vault and Certificate
83 | $azKeyVault = Get-AzKeyVault -VaultName $KeyVaultName
84 | try {
85 | $azKeyVaultSecret = Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $CertificateName -ErrorAction Stop
86 | }
87 | catch {
88 | Write-Host "Error - Check KeyVault '$KeyVaultName' or Certificate '$CertificateName' doesnt Exist" -BackgroundColor DarkRed
89 | Break
90 | }
91 |
92 | } #begin
93 | process
94 | {
95 | #Prepare to export Azure Key Vault certificate to local file
96 | if (($null -eq $azKeyVault) -or ($null -eq $azKeyVaultSecret))
97 | {
98 | Write-Host "Error - Check KeyVault '$KeyVaultName' or Certificate '$CertificateName' doesnt Exist" -BackgroundColor DarkRed
99 | Break
100 | } #if (($null -eq $azKeyVault) -or ($null -eq $azKeyVaultSecret))
101 | else {
102 | Write-Host "Verified - Key Vault and Certificate exists - '$KeyVaultName' and '$CertificateName'" -BackgroundColor DarkGreen
103 | #Put KeyVault Certificate information in memory to export
104 | [PSCredential]$password = New-Object System.Management.Automation.PSCredential('vcloud-lab.com',$azKeyVaultSecret.SecretValue)
105 | $cert64TextString = [System.Convert]::FromBase64String($password.GetNetworkCredential().password)
106 | $x509CertCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
107 | $x509CertCollection.Import($cert64TextString, $null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
108 | if ($PSCmdlet.ParameterSetName -eq 'cer')
109 | {
110 | #Export Azure Key Vault certificate to .cer file
111 | $azKeyVaultCert = Get-AzKeyVaultCertificate -VaultName $keyVaultName -Name $CertificateName
112 | $azKeyVaultCertBytes = $azKeyVaultCert.Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
113 | $cerCertFile = "$certFolderPath\$CertificateName.cer"
114 | [System.IO.File]::WriteAllBytes($cerCertFile, $azKeyVaultCertBytes)
115 | Write-Host "Exported certificate to file - $certFolderPath\$CertificateName.cer"
116 | }
117 | elseif ($PSCmdlet.ParameterSetName -eq 'pfx')
118 | {
119 | #Export Azure Key Vault certificate to .pfx file
120 | $x509CertCollectionBytes = $x509CertCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $PfxCertPassword)
121 | $pfxCertFile = "$certFolderPath\$CertificateName.pfx"
122 | [System.IO.File]::WriteAllBytes($pfxCertFile, $x509CertCollectionBytes)
123 | Write-Host "Exported certificate to file - $certFolderPath\$CertificateName.cer"
124 | }
125 | } #else if (($null -eq $azKeyVault) -or ($null -eq $azKeyVaultSecret))
126 | } #process
127 | end {} #end
128 |
--------------------------------------------------------------------------------
/Azure/Find-AzureBlobFile.ps1:
--------------------------------------------------------------------------------
1 | $searchFile = 'txt|csv|ps1'
2 | $exportCsv = 'c:\temp\files.csv'
3 |
4 | $storageAccount = Get-AzStorageAccount
5 | foreach ($sa in $storageAccount)
6 | {
7 | $saKey = Get-AzStorageAccountKey -ResourceGroupName $sa.ResourceGroupName -Name $sa.StorageAccountName
8 | $saContext = New-AzStorageContext -StorageAccountName $sa.StorageAccountName -StorageAccountKey $saKey[1].Value
9 | $saContainer = Get-AzStorageContainer -Context $saContext
10 | foreach ($saFolder in $saContainer)
11 | {
12 | $files = Get-AzStorageBlob -container $saFolder.Name -Context $saContext | Where-Object {$_.Name -match $searchFile}
13 | $files
14 | $files | Select-Object Name, @{N='StorageAccountName';E={$_.Context.StorageAccountName}}, @{N='Container';E={$saFolder.Name}} | Export-Csv -NoTypeInformation -Path $exportCsv -Append
15 | }
16 | }
--------------------------------------------------------------------------------
/Azure/Generate-AzKeyVaultCertificate.ps1:
--------------------------------------------------------------------------------
1 | [CmdletBinding(
2 | SupportsShouldProcess=$True,
3 | ConfirmImpact='Medium',
4 | HelpURI='http://vcloud-lab.com'
5 | )]
6 |
7 | <#
8 | .SYNOPSIS
9 | Generate new Self Singed certificate in Azure Key Vault
10 |
11 | .DESCRIPTION
12 | This Script generates new Self Singed SSL certificate in Azure Key Vault, it can create new certificate or update create new version in existing key vault certificate.
13 |
14 | .PARAMETER CertificateName
15 | Specify Certificate Name for either new or existing Key vault certificate.
16 |
17 | .PARAMETER KeyVaultName
18 | Specify under which key vault you want to generate or update certificate.
19 |
20 | .INPUTS
21 | None. Generate or update version of certificate on Key Vault.
22 |
23 | .OUTPUTS
24 | Shows information Key Vault Certificate status. You can pipe information to Export-CSV.
25 |
26 | .EXAMPLE
27 | PS> .\Generate AzKeyVaultCertificate.ps1 -CertificateName vcloud-lab-Automation-Account-Ps2 -KeyVaultName vcloudvault
28 |
29 | Found Key Vault Name:- vcloudvault
30 | Processing creation of Azure Key Vault Certificate
31 | 100% Completed. Checking status
32 | Generated Key Vault Certificate successfully
33 |
34 |
35 | Id : https://vcloudvault.vault.azure.net/certificates/vcloud-lab-Automation-Account-Ps2/pending
36 | Status : completed
37 | StatusDetails :
38 | RequestId : 614c70bba71949c88673253402b8cb80
39 | Target : https://vcloudvault.vault.azure.net/certificates/vcloud-lab-Automation-Account-Ps2
40 | Issuer : Self
41 | CancellationRequested : False
42 | CertificateSigningRequest : MIIC6jCCAdICAQAwLDEqMCgGA1UEAxMhdmNsb3VkLWxhYi1BdXRvbWF0aW9uLUFjY291bnQtUHMyMIIfUjANBgkqhkiG9w0BAQEFAAO
43 | CAQ8AMIIBCgKCAQEArXrw896z/7nwBjNsg2+qEk01S2BcV0ju4Fc1usKBgXAk6jO6pzQru5NNT0Lpdvvx6/y+14Tg01ElHwRHYDbKLD
44 | br+ZjglukebAhSt0zn12bf6UrSGmd2e1BC0F0mo7ZNdwLkNaqAY3/y48YIqAltu6sBQV+lZthAS5vrB0cwNpukG/Y3+MkRuEc909RfF
45 | R6IF88Cd5aHvS8i126BbQSYRhFQTr5z+btQx3BtJKivVRzw+M4CxbmHWkpOstUK4JRUfYhAOylwL2e6JFJiHCQNg0dVsb3Mlkp0cgY3
46 | bHoPBa56754agQzWOV3q238CbmbkAw1HmHcjCT+jraHbEdj1pQIDAQABoHkwdwYJKoZIhvcNAQkOMWowaDAOBgNVHQ8BAf8EBAMCBaA
47 | wHQYDVR0lBBYwFAYIKwYBBQUfgwEGCCsGAQUFBwMCMCwGA1UdEQQlMCOCIXZjbG91ZC1sYWItQXV0b21hdGlvbi1BY2NvdW50LVBzMj
48 | AJBgNVHRMEAjAAMA0GCSqGSIb3DQEBCwUAA4IBAQA2Doge8GLk26h2C8QyaBGBfrEsmf3f4BdX8MTfAAWlprnZYNTfjp4S2JFlthyAZ
49 | afjUKyugaz5zX04mwxRS2XhizXafJGLXploGlYSC/s7YCbGlNirM/5k8AfASP4uLfN23/%^DcqHBt34QOcf7IIIyo1TLfCExhy4c9j0
50 | DLS5oVd0wjKZhFasneW0gf/D-|!an8gZ2KlTHiT75LydDSbkKK+Aufzy8Kn2KBVrJ4PQ2UaUBekMe4MLbxkBzL0W7WUNupwZDlOGYQs
51 | ErrorMessage :
52 | Name : vcloud-lab-Automation-Account-Ps2
53 | VaultName : vcloudvault
54 |
55 | .EXAMPLE
56 | PS> .\Generate AzKeyVaultCertificate.ps1 vcloud-lab-Automation-Account-Ps2 vcloudvault
57 | This is another way to execute command .\Generate AzKeyVaultCertificate.ps1 -CertificateName vcloud-lab-Automation-Account-Ps2 -KeyVaultName vcloudvault
58 |
59 | .LINK
60 | Online version: http://vcloud-lab.com
61 |
62 | .LINK
63 | Get-AzVMBackupInformation.ps1
64 | http://vcloud-lab.com/entries/microsoft-azure/get-azure-virtual-machine-backup-reports-using-powershell
65 | #>
66 |
67 | Param
68 | (
69 | [parameter(Position=0)]
70 | [String]$CertificateName = 'vcloud-lab-Automation-Account-Ps',
71 | [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
72 | [alias('KeyVault')]
73 | [String]$KeyVaultName = 'vcloudvault'
74 | ) #Param
75 |
76 | Begin {
77 | #Get existing Azure Key Vault information
78 | $azKeyVault = Get-AzKeyVault -Name $keyVaultName -ErrorAction SilentlyContinue
79 | if ($null -eq $azKeyVault)
80 | {
81 | Write-Host "Didn't find Key Vault with name Azure:- $keyVaultName" -BackgroundColor DarkRed
82 | break
83 | }
84 | else
85 | {
86 | Write-Host "Found Key Vault Name:- $keyVaultName" -BackgroundColor DarkGreen
87 | }
88 | } #Begin
89 | Process {
90 | #Generate new Azure Key Vault Certificate
91 | Write-Host "Processing creation of Azure Key Vault Certificate" -ForegroundColor Yellow
92 | $certSubjectName = 'cn=' + $CertificateName
93 | $azKeyVaultCertPolicy = New-AzKeyVaultCertificatePolicy -SecretContentType "application/x-pkcs12" -SubjectName $certSubjectName -IssuerName Self -ValidityInMonths 24 -ReuseKeyOnRenewal -DnsName $certificateName
94 | $azKeyVaultCertStatus = Add-AzKeyVaultCertificate -VaultName $keyVaultName -Name $CertificateName -CertificatePolicy $azKeyVaultCertPolicy
95 |
96 | #Wait for certificate to generate
97 | $counter = 1
98 | While ($azKeyVaultCertStatus.Status -eq 'inProgress') {
99 | Start-Sleep -Milliseconds 50
100 | Write-Host "`r$counter% creation in progress" -NoNewline -ForegroundColor Yellow
101 | $azKeyVaultCertStatus = Get-AzKeyVaultCertificateOperation -VaultName $keyVaultName -Name $CertificateName
102 | $counter++
103 | }
104 | Write-Host "`r100% Completed. Checking status... " -ForegroundColor Yellow
105 | if ($azKeyVaultCertStatus.Status -ne 'completed') {
106 | Write-Host $($azKeyVaultCertStatus.StatusDetails) -ForegroundColor Magenta
107 | }
108 | else {
109 | Write-Host "Generated Key Vault Certificate successfully" -BackgroundColor DarkGreen
110 | Write-Output $azKeyVaultCertStatus
111 | }
112 | } #Process
113 | End {} #end
--------------------------------------------------------------------------------
/Azure/Get-AzKeyVaultSecret.ps1:
--------------------------------------------------------------------------------
1 | #http://vcloud-lab.com
2 | #created by janvi on 1st april 2020
3 |
4 | Connect-AzAccount
5 |
6 | Get-AzKeyVault
7 |
8 | Get-AzKeyVaultSecret -VaultName "Key Vault Name"
9 |
10 | $secret = Get-AzKeyVaultSecret -VaultName "Key Vault Name" -Name "Secret Name"
11 | $key = ConvertFrom-SecureString $secret.SecretValue
12 |
13 | $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue)
14 | $password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
15 | $password
16 |
--------------------------------------------------------------------------------
/Azure/Get-AzKeyVaultSecretValue.ps1:
--------------------------------------------------------------------------------
1 | #Created by http://vcloud-lab.com
2 |
3 | $credential = Get-Credential -UserName vaultviewer@bishopal.com -Message 'Microsoft Azure Login'
4 | Connect-AzAccount -Credential $credential
5 |
6 | $keyVaulttoken = Get-AzAccessToken -ResourceUrl https://vault.azure.net
7 | #az account get-access-token --resource https://vault.azure.net | ConvertFrom-Json
8 |
9 | $headers = @{"Authorization" = "Bearer $($keyVaulttoken.Token)"}
10 | $response = Invoke-RestMethod -Uri https://vcloud02vault.vault.azure.net/secrets/RootSecret/03d6fd62056a4790a8982b1a75f320f8?api-version=7.1 -Headers $headers
11 |
12 | $response.value
13 |
--------------------------------------------------------------------------------
/Azure/Get-AzVMBackupInformation.ps1:
--------------------------------------------------------------------------------
1 | [CmdletBinding(SupportsShouldProcess=$True,
2 | ConfirmImpact='Medium',
3 | HelpURI='http://vcloud-lab.com',
4 | DefaultParameterSetName = 'AllVirtualMachines'
5 | )]
6 |
7 | <#
8 | .SYNOPSIS
9 | Collect Azure VM Backup Information
10 |
11 | .DESCRIPTION
12 | This Script collects Azure Virtual Machine Backup Recovery service vault information, This report includes the complete backup status Information of VM.
13 |
14 | .PARAMETER AllVirtualMachines
15 | Collect Backup information of the all Azure Virtual Machines, This is default parameter.
16 |
17 | .PARAMETER VirtualMachineList
18 | You can specify for which virtual machine you want backup information.
19 |
20 | .INPUTS
21 | None. Provides virtual machine information.
22 |
23 | .OUTPUTS
24 | Generate Backup information. You can pipe information to Export-CSV.
25 |
26 | .EXAMPLE
27 | PS> .\Get-AzVMBackupInformation.ps1
28 |
29 | VM_Name : vcloud-lab-vm01
30 | VM_Location : uksouth
31 | VM_ResourceGroupName : VCLOUD-LAB.COM
32 | VM_BackedUp : True
33 | VM_RecoveryVaultName : vault828
34 | VM_RecoveryVaultPolicy : DailyPolicy-kosrnox0
35 | VM_BackupHealthStatus : Passed
36 | VM_BackupProtectionStatus : Healthy
37 | VM_LastBackupStatus : Completed
38 | VM_LastBackupTime : 27-05-2021 19:32:34
39 | VM_BackupDeleteState : NotDeleted
40 | VM_BackupLatestRecoveryPoint : 27-05-2021 19:32:37
41 | VM_Id : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VCLOUD-LAB.COM/providers/Microsoft.Compute/virtualMachines/vcloud-lab-vm01
42 | RecoveryVault_ResourceGroupName : vCloud-lab.com
43 | RecoveryVault_Location : uksouth
44 | RecoveryVault_SubscriptionId : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vCloud-lab.com/providers/Microsoft.RecoveryServices/vaults/vault828
45 |
46 | .EXAMPLE
47 | PS> .\Get-AzVMBackupInformation.ps1 -AllVirtualMachines
48 | This produces same result as .\Get-AzVMBackupInformation.ps1 from all VMs
49 |
50 | .EXAMPLE
51 | PS> .\Get-AzVMBackupInformation.ps1 -VirtualMachineList
52 | Provide either single virtual machine name or in list
53 |
54 | .LINK
55 | Online version: http://vcloud-lab.com
56 |
57 | .LINK
58 | Get-AzVMBackupInformation.ps1
59 | #>
60 | Param
61 | (
62 | [parameter(Position=0, ParameterSetName = 'AllVMs' )]
63 | [Switch]$AllVirtualMachines,
64 | [parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'VM' )]
65 | [alias('Name')]
66 | [String[]]$VirtualMachineList
67 | ) #Param
68 | Begin
69 | {
70 | #Collecing Azure virtual machines Information
71 | Write-Host "Collecing Azure virtual machine Information" -BackgroundColor DarkGreen
72 | if (($PSBoundParameters.ContainsKey('AllVirtualMachines')) -or ($PSBoundParameters.Count -eq 0))
73 | {
74 | $vms = Get-AzVM
75 | } #if ($PSBoundParameters.ContainsKey('AllVirtualMachines'))
76 | elseif ($PSBoundParameters.ContainsKey('VirtualMachineList'))
77 | {
78 | $vms = @()
79 | foreach ($vmname in $VirtualMachineList)
80 | {
81 | $vms += Get-AzVM -Name $vmname
82 |
83 | } #foreach ($vmname in $VirtualMachineList)
84 | } #elseif ($PSBoundParameters.ContainsKey('VirtualMachineList'))
85 |
86 | #Collecing All Azure backup recovery vaults Information
87 | Write-Host "Collecting all Backup Recovery Vault information" -BackgroundColor DarkGreen
88 | $backupVaults = Get-AzRecoveryServicesVault
89 | } #Begin
90 | Process
91 | {
92 | $vmBackupReport = [System.Collections.ArrayList]::new()
93 | foreach ($vm in $vms)
94 | {
95 | $recoveryVaultInfo = Get-AzRecoveryServicesBackupStatus -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Type 'AzureVM'
96 | if ($recoveryVaultInfo.BackedUp -eq $true)
97 | {
98 | Write-Host "$($vm.Name) - BackedUp : Yes"
99 | #Backup Recovery Vault Information
100 | $vmBackupVault = $backupVaults | Where-Object {$_.ID -eq $recoveryVaultInfo.VaultId}
101 |
102 | #Backup recovery Vault policy Information
103 | $container = Get-AzRecoveryServicesBackupContainer -ContainerType AzureVM -VaultId $vmBackupVault.ID -FriendlyName $vm.Name #-Status "Registered"
104 | $backupItem = Get-AzRecoveryServicesBackupItem -Container $container -WorkloadType AzureVM -VaultId $vmBackupVault.ID
105 | } #if ($recoveryVaultInfo.BackedUp -eq $true)
106 | else
107 | {
108 | Write-Host "$($vm.Name) - BackedUp : No" -BackgroundColor DarkRed
109 | $vmBackupVault = $null
110 | $container = $null
111 | $backupItem = $null
112 | } #else if ($recoveryVaultInfo.BackedUp -eq $true)
113 |
114 | [void]$vmBackupReport.Add([PSCustomObject]@{
115 | VM_Name = $vm.Name
116 | VM_Location = $vm.Location
117 | VM_ResourceGroupName = $vm.ResourceGroupName
118 | VM_BackedUp = $recoveryVaultInfo.BackedUp
119 | VM_RecoveryVaultName = $vmBackupVault.Name
120 | VM_RecoveryVaultPolicy = $backupItem.ProtectionPolicyName
121 | VM_BackupHealthStatus = $backupItem.HealthStatus
122 | VM_BackupProtectionStatus = $backupItem.ProtectionStatus
123 | VM_LastBackupStatus = $backupItem.LastBackupStatus
124 | VM_LastBackupTime = $backupItem.LastBackupTime
125 | VM_BackupDeleteState = $backupItem.DeleteState
126 | VM_BackupLatestRecoveryPoint = $backupItem.LatestRecoveryPoint
127 | VM_Id = $vm.Id
128 | RecoveryVault_ResourceGroupName = $vmBackupVault.ResourceGroupName
129 | RecoveryVault_Location = $vmBackupVault.Location
130 | RecoveryVault_SubscriptionId = $vmBackupVault.ID
131 | }) #[void]$vmBackupReport.Add([PSCustomObject]@{
132 | } #foreach ($vm in $vms)
133 | } #Process
134 | end
135 | {
136 | $vmBackupReport
137 | } #end
138 |
--------------------------------------------------------------------------------
/Azure/Get-AzureReservationsVM.ps1:
--------------------------------------------------------------------------------
1 | #Install Az.Reservations Module if not exists.
2 | #Install-Module -Name Az.Reservations -Scope CurrentUser
3 |
4 | #Start and End date to fetch consumption usage details of Azure Reservations
5 | $startDate = '04-01-2021'
6 | $endDate = '05-10-2021'
7 |
8 | #List all Azure subscriptions
9 | $subscriptionIds = Get-AzSubscription
10 | foreach ($subscription in $subscriptionIds) {
11 | #Change the Subscription
12 | Set-AzContext -Subscription $subscription
13 | #Get the information of Azure Reservation consumption usage details
14 | $info = Get-AzConsumptionUsageDetail -StartDate $startDate -EndDate $endDate
15 | #Save the information to Microsoft Excel CSV files with subscription id in the name of file
16 | $info | Export-Csv -NoTypeInformation -Path "C:\temp\$subscription.csv"
17 | }
--------------------------------------------------------------------------------
/Azure/Get-AzureVirtualNetworkInfo.ps1:
--------------------------------------------------------------------------------
1 | #created by: janvi | vcloud-lab.com
2 | #date created: 10 December 2021
3 | #purpose: Gather Azure Virtual Network information in CSV file
4 |
5 | $vNets = Get-AzVirtualNetwork
6 |
7 | foreach ($vNet in $vNets) {
8 | $subnetList = @()
9 | foreach ($subnet in $vNet.Subnets) {
10 | $subnetList += "[ $($subnet.Name) | $($vNet.Subnets.AddressPrefix -join ', ') ] "
11 | }
12 |
13 | $vnetPeeringList = @()
14 | foreach ($vnetPeering in $vNet.VirtualNetworkPeerings) {
15 | $remoteVNET = $vNet.VirtualNetworkPeerings.RemoteVirtualNetwork
16 | $remoteVNETName = ($remoteVNET | foreach-Object {Split-Path $_.Id -leaf}) -join ', '
17 | $remoteVNETAddressSpace = $vNet.VirtualNetworkPeerings.RemoteVirtualNetworkAddressSpace.AddressPrefixes -join ', '
18 | $vnetPeeringList += "[ $($vnetPeering.Name) | $($vnetPeering.PeeringState) | $remoteVNETName | $remoteVNETAddressSpace ] "
19 | }
20 |
21 | [PSCustomObject]@{
22 | Name = $vNet.Name
23 | ResourceGroupName = $vNet.ResourceGroupName
24 | Location = $vNet.Location
25 | Id = $vNet.Id
26 | AddressSpace = $vNet.AddressSpace.AddressPrefixes -join ', '
27 | Subnets = $subnetList -join ', '
28 | VnetPeerings = $vnetPeeringList -join ', '
29 | EnableDdosProtection = $vNet.EnableDdosProtection
30 | }
31 | }
--------------------------------------------------------------------------------
/Azure/Get-ManagedIdentityKeyVaultSecret.ps1:
--------------------------------------------------------------------------------
1 | CreatedBy: http://vcloud-lab.com
2 |
3 | $env:COMPUTERNAME; $env:USERNAME
4 |
5 | $response = Invoke-RestMethod -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net' -Method GET -Headers @{Metadata="true"}
6 |
7 | $response.access_token
8 |
9 | $result = Invoke-RestMethod -Uri https://vcloud02vault.vault.azure.net/secrets/RootSecret/03d6fd62056a4790a8982b1a75f320f8?api-version=7.1 -Headers @{"Authorization" = "Bearer $($response.access_token)"}
10 |
11 | $result | select id, value, contentType
12 |
--------------------------------------------------------------------------------
/Azure/New-AzADAppRegistrations:
--------------------------------------------------------------------------------
1 | #Created by http://vcloud-lab.com
2 |
3 | #PowerShell az example
4 | New-AzADApplication -DisplayName TestApp -AvailableToOtherTenants $false -IdentifierUris 'http://localhost'
5 |
6 | #Powershell AzureAD example
7 | Import-Module AzureAD
8 | Connect-AzureAD
9 | $azureADAppReg = New-AzureADApplication -DisplayName TestApp -AvailableToOtherTenants $false
10 | $azureADAppReg
11 | New-AzureADApplicationPasswordCredential -CustomKeyIdentifier PrimarySecret -ObjectId $azureADAppReg.ObjectId -EndDate ((Get-Date).AddMonths(6))
12 |
13 | $certPath = 'C:\Temp\testcert.cer'
14 | $cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($certPath)
15 | $keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
16 | $base64Thumbprint = [System.Convert]::ToBase64String($cert.GetCertHash())
17 | New-AzureADApplicationKeyCredential -ObjectId $azureADAppReg.ObjectId -CustomKeyIdentifier $base64Thumbprint -Type AsymmetricX509Cert -Usage Verify -Value $keyValue -EndDate (Get-Date).AddMonths(6)
18 |
19 | #AzureCLI example
20 | az login
21 | az ad app create --display-name TestApp01 --available-to-other-tenants false
22 | az ad app credential reset --id bd195084-8bea-43cf-a6bb-076ca70e6a48 --credential-description TestSecret
23 | az ad app credential reset --id bd195084-8bea-43cf-a6bb-076ca70e6a48 --cert "@C:\Temp\testcert.cer" --append
24 |
--------------------------------------------------------------------------------
/Azure/New-AzAutomationAccountRunAs.ps1:
--------------------------------------------------------------------------------
1 | #Written By - vcloud-lab.com #vJanvi
2 | #Create new Azure Automation Account Run As
3 |
4 | $automationAccount = 'AutomationAC01'
5 | $certExpiryMonths = 24
6 | $certPfxPassword = '123456'
7 | $certExportPath = 'C:\Temp\Certs'
8 | $resourceGroup = 'vCloud-lab.com'
9 | $location = "East Us"
10 |
11 | $certPassword = ConvertTo-SecureString $certPfxPassword -AsPlainText -Force
12 |
13 | #Region
14 | #Generate SSL certificate
15 | Write-Host "Generate self signed certificate for - $automationAccount"
16 | $selfSignedCertSplat = @{
17 | DnsName = $automationAccount
18 | Subject = $automationAccount
19 | CertStoreLocation = 'cert:\CurrentUser\My'
20 | KeyExportPolicy = 'Exportable'
21 | Provider = 'Microsoft Enhanced RSA and AES Cryptographic Provider'
22 | NotAfter = (Get-Date).AddMonths($certExpiryMonths)
23 | HashAlgorithm = 'SHA256'
24 | }
25 | $selfSignedCert = New-SelfSignedCertificate @selfSignedCertSplat
26 |
27 | #Export SSL certificate to files
28 | Write-Host "Export self signed certificate to folder - $certExportPath"
29 | $certThumbPrint = 'cert:\CurrentUser\My\' + $selfSignedCert.Thumbprint
30 | Export-PfxCertificate -Cert $certThumbPrint -FilePath "$certExportPath\$automationAccount.pfx" -Password $certPassword -Force | Write-Verbose
31 | Export-Certificate -Cert $certThumbPrint -FilePath "$certExportPath\$automationAccount.cer" -Type CERT | Write-Verbose
32 | #EndRegion - Generate self signed certificate
33 |
34 | #Region
35 | #Read PFX Certificate
36 | Write-Host "Read PFX file"
37 | $pfxCertSplat = @{
38 | TypeName = 'System.Security.Cryptography.X509Certificates.X509Certificate2'
39 | ArgumentList = @("$certExportPath\$automationAccount.pfx", $certPfxPassword)
40 | }
41 | $pfxCert = New-Object @pfxCertSplat
42 |
43 | #Create an Azure AD application (App Registrations)
44 | Write-Host "Create Azure AD application - $automationAccount"
45 | $azADAppRegistrationsSplat = @{
46 | DisplayName = $automationAccount
47 | HomePage = "http://$automationAccount"
48 | IdentifierUris = "http://$automationAccount"
49 | }
50 | $azADAppRegistrations = New-AzADApplication @azADAppRegistrationsSplat
51 |
52 | #Create Azure active directory Application Credential (App Registrations)
53 | Write-Host "Create credential for Azure AD application - $automationAccount"
54 | $azADAppRegistrationsCredSplat = @{
55 | ApplicationId = $azADAppRegistrations.ApplicationId
56 | CertValue = [System.Convert]::ToBase64String($pfxCert.GetRawCertData())
57 | StartDate = $pfxCert.NotBefore
58 | EndDate = $pfxCert.NotAfter
59 | }
60 | [void](New-AzADAppCredential @azADAppRegistrationsCredSplat)
61 |
62 | #Azure AD Service Principal
63 | Write-Host "Create Azure AD Service Principal - $automationAccount"
64 | [void](New-AzADServicePrincipal -ApplicationId $azADAppRegistrations.ApplicationId)
65 | Start-Sleep -Seconds 15
66 |
67 | #Provide contributer access on Serivce Principal
68 | Write-Host "Assign contributer azure role on Azure AD application / SP - $automationAccount"
69 | $AzRoleAssignment = New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $azADAppRegistrations.ApplicationId -ErrorAction SilentlyContinue
70 | $i = 0;
71 | While (($null -eq $AzRoleAssignment) -and ($i -le 6))
72 | {
73 | Start-Sleep -Seconds 10
74 | New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $azADAppRegistrations.ApplicationId -ErrorAction SilentlyContinue
75 | $AzRoleAssignment = Get-AzRoleAssignment -ServicePrincipalName $azADAppRegistrations.ApplicationId -ErrorAction SilentlyContinue
76 | $i++
77 | }
78 | #EndRegion - Azure AD application
79 |
80 | #Region
81 | Write-Host "Create Azure Automation Account - $automationAccount"
82 | [void](New-AzAutomationAccount -Name $automationAccount -Location $location -ResourceGroupName $resourceGroup)
83 |
84 | Write-Host "Create Azure Automation Account Run as certificate - $automationAccount"
85 | Start-Sleep -Seconds 15
86 | $azAutomationCertSplat = @{
87 | ResourceGroupName = $resourceGroup
88 | AutomationAccountName = $automationAccount
89 | Path = "$certExportPath\$automationAccount.pfx"
90 | Name = 'AzureRunAsCertificate' #$automationAccount
91 | Password = $certPassword
92 | Description = "This certificate is used to authenticate with the service principal that was automatically created for this account. For details on this service principal and certificate, or to recreate them, go to this account’s Settings. For example usage, see the tutorial runbook in this account."
93 | }
94 | [void](New-AzAutomationCertificate @azAutomationCertSplat -Exportable:$true)
95 |
96 | Write-Host "Create Azure Automation Account connection - $automationAccount"
97 | Start-Sleep -Seconds 15
98 | $azSubscriptionContext = Get-AzContext
99 | $azAutomationConnectionSplat = @{
100 | ResourceGroupName = $resourceGroup
101 | AutomationAccountName = $automationAccount
102 | Name = 'AzureRunAsConnection' #$automationAccount
103 | ConnectionTypeName = 'AzureServicePrincipal'
104 | Description = "This connection contains information about the service principal that was automatically created for this automation account. For details on this service principal and its certificate, or to recreate them, go to this account’s Settings. For example usage, see the tutorial runbook in this account."
105 | ConnectionFieldValues = @{
106 | ApplicationId = $azADAppRegistrations.ApplicationId.Guid
107 | TenantId = $azSubscriptionContext.Tenant.Id
108 | CertificateThumbprint = $pfxCert.Thumbprint
109 | SubscriptionId = $azSubscriptionContext.Subscription
110 | }
111 | }
112 | [void](New-AzAutomationConnection @azAutomationConnectionSplat)
113 | #EndRegion
--------------------------------------------------------------------------------
/Azure/New-CliAzKeyVault.ps1:
--------------------------------------------------------------------------------
1 | #AzureCLI create azure key vault
2 | #created by http://vcloud-lab.com
3 |
4 | az login
5 |
6 | az keyvault create --name vCloud02Vault --resource-group vcloud-lab.com --location 'East US' --sku Standard
7 |
8 | az keyvault secret set-attributes --name RootSecret --vault-name vCloud02Vault --content-type 'Esxi Root Password'
9 |
10 | az ad user show --id vaultviewer@vcloud-lab.com
11 | az keyvault set-policy --name vCloud02Vault --object-id 8ab61685-c967-460d-8152-7d41b54449fe --secret-permissions get list
12 |
13 | az role assignment create --assignee vaultviewer@vcloud-lab.com --role 'Key Vault Reader' --scope /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud02Vault
14 |
15 | az login
16 | az keyvault secret show --name RootSecret --vault-name vCloud02Vault
17 |
--------------------------------------------------------------------------------
/Azure/New-PsAzKeyVault.ps1:
--------------------------------------------------------------------------------
1 | #Micorosft azure create new key vault Powershell
2 | #created by: http://vcloud-lab.com
3 |
4 | Connect-AzAccount
5 |
6 | $vaultName = 'vCloud01Vault'
7 | $resourceGroupName = 'vcloud-lab.com'
8 | $secretName = 'RootSecret'
9 | $userPrincipalName = 'vaultviewer@vcloud-lab.com'
10 |
11 | New-AzKeyVault -Name $vaultName -ResourceGroupName $resourceGroupName -Location 'East US' -Sku Standard
12 |
13 | Get-AzkeyVault -VaultName $vaultName
14 |
15 | $secretValue = ConvertTo-SecureString -String 'T0p$ecret' -AsPlainText -Force
16 | Set-AzKeyVaultSecret -VaultName $vaultName -Name $secretName -SecretValue $secretValue -ContentType 'ESXi root password'
17 |
18 | Set-AzKeyVaultAccessPolicy -VaultName $vaultName -UserPrincipalName $userPrincipalName -PermissionsToSecrets Get,List
19 |
20 | $keyVault = Get-AzkeyVault -VaultName $vaultName
21 | $keyVault.ResourceID
22 |
23 | New-AzRoleAssignment -SignInName $userPrincipalName -RoleDefinitionName 'Key Vault Reader' -Scope $keyVault.ResourceID
24 |
25 | Connect-AzAccount
26 | $keyVaultSecret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $secretName
27 | $password = ConvertFrom-SecureString $keyVaultSecret.SecretValue -AsPlainText
28 | $password
29 |
--------------------------------------------------------------------------------
/Azure/resource_group_azure_ARM_template_PowerShell.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/Azure/resource_group_azure_ARM_template_PowerShell.zip
--------------------------------------------------------------------------------
/Azure_Bicep_Subscription_Usage_Quota_Rule.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/Azure_Bicep_Subscription_Usage_Quota_Rule.zip
--------------------------------------------------------------------------------
/Azure_Rest_API_PowerShell/PowerShellAzModuleAzureRestAPI.ps1:
--------------------------------------------------------------------------------
1 | # Install the Az PowerShell module if not already installed
2 | #Install-Module -Name Az
3 |
4 | # Import the Az PowerShell module
5 | Import-Module -Name Az
6 |
7 | # Set your Azure credentials
8 | # $username = 'janvi@onmicrsoft.com'
9 | # $password = ' '| ConvertTo-SecureString -AsPlainText -Force
10 | # $cred = New-Object System.Management.Automation.PSCredential ($username, $password)
11 |
12 | # Login to Azure
13 | Connect-AzAccount #-Credential $cred
14 |
15 | # Get the access token
16 | $token = Get-AzAccessToken
17 |
18 | # Use the access token to authenticate your Azure REST API requests
19 | $headers = @{
20 | "Authorization" = "Bearer $($token.Token)"
21 | "Content-Type" = "application/json"
22 | }
23 |
24 | # List subscriptions using Azure REST API request
25 | $url = "https://management.azure.com/subscriptions?api-version=2021-04-01"
26 | $response = Invoke-RestMethod -Uri $url -Method Get -Headers $headers
27 | $response.value
28 |
29 | # List Resource Groups using Azure REST API request
30 | $subscription = Get-AzSubscription -SubscriptionName 'Sponsership-by-Microsoft'
31 |
32 | $url = "https://management.azure.com/subscriptions/$($subscription.Id)/resourcegroups?api-version=2021-04-01"
33 | $response = Invoke-RestMethod -Uri $url -Method Get -Headers $headers
34 | $response.value
--------------------------------------------------------------------------------
/Azure_Rest_API_PowerShell/PowerShellAzureRestApiExample.ps1:
--------------------------------------------------------------------------------
1 | #Documentation
2 | #https://learn.microsoft.com/en-us/rest/api/azure/
3 | #https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow#get-a-token
4 |
5 | # Define the resources - resource group and storage account details
6 | $resourceGroupName = "prod.vcloud-lab.com"
7 | $resourceGroupLocation = "West US"
8 | $storageAccountName = "vcloudlabsaprod"
9 |
10 | # Define your Azure subscription ID and an access token
11 | $subscriptionId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
12 | $tenantId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
13 | $clientId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
14 | $clientSecret = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
15 |
16 | # Body information for http authentication
17 | $body = @{
18 | grant_type = "client_credentials"
19 | client_id = $clientId
20 | client_secret = $clientSecret
21 | resource = "https://management.azure.com/"
22 | }
23 |
24 | # Create
25 | $response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body
26 | $accessToken = $response.access_token
27 |
28 | # Headers for the API requests
29 | $headers = @{
30 | "Authorization" = "Bearer $accessToken"
31 | "Content-Type" = "application/json"
32 | }
33 |
34 | Write-Host 'Creating Resource Group in Azure'
35 | #https://learn.microsoft.com/en-us/rest/api/resources/resource-groups?view=rest-resources-2021-04-01
36 | #https://learn.microsoft.com/en-us/rest/api/resources/resource-groups/create-or-update?view=rest-resources-2021-04-01&tabs=HTTP
37 | # Create the resource group
38 | $resourceGroupUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($resourceGroupName)?api-version=2021-04-01"
39 | $resourceGroupBody = @{
40 | location = $resourceGroupLocation
41 | } | ConvertTo-Json
42 |
43 | $rgResponse = Invoke-RestMethod -Method Put -Uri $resourceGroupUri -Headers $headers -Body $resourceGroupBody
44 |
45 | Start-Sleep -Seconds 10
46 |
47 | while ($rgResponse.properties.provisioningState -ne 'Succeeded') {
48 | Start-Sleep -Seconds 2
49 | }
50 |
51 | Write-Host 'Creating Storage Account in Azure'
52 | #https://learn.microsoft.com/en-us/rest/api/storagerp/storage-sample-create-account
53 | # Create the storage account
54 | $storageAccountUri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Storage/storageAccounts/$($storageAccountName)?api-version=2021-04-01"
55 | $storageAccountBody = @{
56 | location = $resourceGroupLocation
57 | kind = "StorageV2"
58 | sku = @{
59 | name = "Standard_LRS"
60 | }
61 | } | ConvertTo-Json
62 |
63 | Invoke-RestMethod -Method Put -Uri $storageAccountUri -Headers $headers -Body $storageAccountBody
64 |
65 | Start-Sleep -Seconds 10
66 |
67 | Write-Host "Resource group and storage account created successfully."
68 |
69 | <#
70 |
71 | ###################################
72 | # Delete method with different token scope example
73 | ###################################
74 |
75 | #https://learn.microsoft.com/en-us/rest/api/resources/resource-groups/delete?view=rest-resources-2021-04-01&tabs=HTTP
76 | #https://learn.microsoft.com/en-us/rest/api/resources/resources/list-by-resource-group?view=rest-resources-2021-04-01
77 |
78 | #Get resources information inside resource group
79 | $resourceGroupResourcesUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$resourceGroupName/resources?api-version=2021-04-01"
80 | $resourcesResponse = Invoke-RestMethod -Method Get -Uri $resourceGroupResourcesUri -Headers $headers
81 |
82 |
83 | # Delete resource group
84 | $resourceGroupUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($resourceGroupName)?api-version=2021-04-01" ##?forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets&api-version=2021-04-01
85 | Invoke-RestMethod -Method Delete -Uri $resourceGroupUri -Headers $headers
86 |
87 | # Only works for virtual machines and vmss
88 | #$allResourcesType = $resourcesResponse.value.type -join ','
89 | #$resourceGroupUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($resourceGroupName)?forceDeletionTypes=$allResourcesType&api-version=2021-04-01"
90 |
91 | #>
92 |
93 | <# Another Way to get access token
94 | #https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow#get-a-token
95 | #curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'client_id=00001111-aaaa-2222-bbbb-3333cccc4444&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=A1bC2dE3f...&grant_type=client_credentials' 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
96 |
97 | $body = @{
98 | client_id = $clientId
99 | client_secret = $clientSecret
100 | scope = "https://graph.microsoft.com/.default"
101 | grant_type = "client_credentials"
102 | } #| ConvertTo-Json -Compress
103 |
104 | $bodyEncoded = ($body.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join "&"
105 |
106 | $response = Invoke-WebRequest -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -Body $bodyEncoded -ContentType 'application/x-www-form-urlencoded'
107 | $token = $response.Content | ConvertFrom-Json
108 | $token.access_token
109 | #>
--------------------------------------------------------------------------------
/CPU_Quota_Alert_Azure_ARM_templates.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/CPU_Quota_Alert_Azure_ARM_templates.zip
--------------------------------------------------------------------------------
/EncryptDecrypt_PasswordTool.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/janviudapi/PowerShell/4f00fa1c508219e854ae3ac03a18f7e4ac6abecd/EncryptDecrypt_PasswordTool.zip
--------------------------------------------------------------------------------
/ExchangeOnline_Office365/Add-DistributionGroupEmailAddresses.ps1:
--------------------------------------------------------------------------------
1 | Import-Module -Name ExchangeOnlineManagement
2 | Connect-ExchangeOnline
3 |
4 | #$groupInfo = Get-DistributionGroup "NoReply DLP"
5 | #Set-DistributionGroup "NoReply DLP" -EmailAddresses @{Add=$groupInfo.PrimarySmtpAddress,'j@test.com'}
6 |
7 | $rawCsv = Import-CSV C:\Scripts\test\Test.csv
8 | $csvData = $rawCsv | Group-Object-PropertyPrimarySmtpAddress
9 |
10 | foreach ($csv in $csvData)
11 | {
12 | $name=$csv.Name
13 | Write-Host "Working on Distribution Group - $name"-BackgroundColorDarkGreen
14 |
15 | #$groupInfo = Get-DistributionGroup $name
16 | #$existingSecEmails = $groupInfo.EmailAddresses.ForEach({$_.replace('smtp:', '')}) | Where-Object {$_ -cnotmatch 'SMTP:'}
17 | foreach ($secEmail in $csv.Group)
18 | {
19 | $secEmailAddress=$secEmail.secemail
20 | Write-Host"Adding secondary email / Alias - $secEmailAddress"#-BackgroundColor Yellow -ForegroundColor Black
21 | Set-DistributionGroup $csv.Group[0].PrimarySmtpAddress -EmailAddresses @{Add="smtp:$secEmailAddress"}
22 | }
23 | }
--------------------------------------------------------------------------------
/Generate-XMLWithNetObject1.ps1:
--------------------------------------------------------------------------------
1 | #Writen By: vJanvi
2 | #Website: http://vcloud-lab.com
3 | #Purpose: Generate XML Document
4 |
5 | function Set-Log
6 | {
7 | [CmdletBinding(
8 | SupportsShouldProcess=$True,
9 | ConfirmImpact='Medium',
10 | HelpURI='http://vcloud-lab.com'
11 | )] #[CmdletBinding(
12 | Param
13 | (
14 | [parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
15 | [alias('C')]
16 | [String]$FilePath = 'C:\Temp\logs\info.log'
17 | ) #Param
18 | Begin {} #Begin
19 | Process
20 | {
21 | if (Test-Path $FilePath)
22 | {
23 | $parentPath = Split-Path -Path $FilePath -Parent
24 | $fileName = [System.IO.Path]::GetFileNameWithoutExtension($FilePath)
25 | $fileExtension = [System.IO.Path]::GetExtension($FilePath)
26 | $dateTime = [System.DateTime]::Now
27 | $oldFileName = "{0}\$fileName-{1}{2:d2}{3:d2}{4}{5}$fileExtension" -f $parentPath, $dateTime.Year ,$dateTime.Month, $dateTime.Day, $dateTime.ToShortTimeString().Replace(':',''), $dateTime.Millisecond
28 | try
29 | {
30 | Rename-Item -Path $FilePath -NewName $oldFileName -Force -ErrorAction Stop
31 | Write-Host "Renamed filename - $oldFileName" -ForegroundColor DarkYellow
32 | [Void](New-Item -Path $FilePath -ItemType File -Force -ErrorAction Stop)
33 | Write-Host "File created - $FilePath" -ForegroundColor DarkGreen
34 | }
35 | catch
36 | {
37 | Write-Host "File cannot be renamed or created, Check Permission or if in use - $FilePath" -BackgroundColor DarkRed
38 | }
39 |
40 | } #if (Test-Path $filePath)
41 | else
42 | {
43 | try
44 | {
45 | [Void](New-Item -Path $FilePath -ItemType File -Force -ErrorAction Stop)
46 | Write-Host "File created - $FilePath" -ForegroundColor DarkGreen
47 | }
48 | catch
49 | {
50 | Write-Host "File cannot be created, Check Permission or if in use - $FilePath" -BackgroundColor DarkRed
51 | }
52 | } #else
53 | } #Process
54 | End {} #End
55 | } #function Set-log
56 |
57 | Set-log 'C:\Temp\logs\info.log'
58 |
59 | #Referenace Document
60 | #https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlwriter.writeprocessinginstruction?view=net-5.0
61 |
62 | #$filePath = 'C:\Temp\logs\info.log'
63 | #Step by step Article to create a XML Document using
64 |
65 | #Use XmlWriterSettings .net Object and Configure The XML format settings
66 | $xmlsettings = New-Object System.Xml.XmlWriterSettings
67 | $xmlsettings.Indent = $true
68 | $indentChars = $(' ' * 4)
69 | $xmlsettings.IndentChars = $indentChars
70 |
71 | #Create a empty XML file under given path with XML Settings
72 | $xmlWriterObj = [System.XML.XmlWriter]::Create($filePath, $xmlsettings)
73 |
74 | # Write the XML Declaration and set the XSL
75 | $xmlWriterObj.WriteStartDocument()
76 |
77 | #Define Additional XML format (Write the Processing Instruction node.)
78 | $xmlWriterObj.WriteProcessingInstruction('xml-stylesheet', "type='text/xsl' href='style.xsl'")
79 |
80 | #Define the DocumentType node
81 | $xmlWriterObj.WriteDocType('rootinfo', $null , $null, '')
82 |
83 | #Define a Comment node
84 | $xmlWriterObj.WriteComment("sample XML")
85 |
86 | #Define Start the Root Element
87 | $xmlWriterObj.WriteStartElement("Root") # <-- Start Element
88 |
89 | $xmlWriterObj.WriteStartElement('Object') # <-- Start Element
90 |
91 | $xmlWriterObj.WriteElementString('PropertyKey01','Value01') # <-- Add Property key Value pair 1 Element
92 | $xmlWriterObj.WriteElementString('PropertyKey02','Value02') # <-- Add Property key Value pair 2 Element
93 | $xmlWriterObj.WriteElementString('PropertyKey03','Value03') # <-- Add Property key Value pair 2 Element
94 |
95 | $xmlWriterObj.WriteStartElement("SubChildObject") # <-- Start
96 |
97 | $xmlWriterObj.WriteEntityRef("h") #<-- add style and data
98 | $xmlWriterObj.WriteElementString("SubPropertyKey01","Value01")
99 | $xmlWriterObj.WriteElementString("SubPropertyKey02","Value02")
100 |
101 | $xmlWriterObj.WriteEndElement() # <-- Add End
102 |
103 | $xmlWriterObj.WriteEndElement() # <-- Add End