Azure PowerShell. Reference Virtual Network From Another Resource Group - azure-powershell

I have a PowerShell script that restrict access to Web Apps down to a subnet from a Virtual Network:
Param (
[Parameter(Mandatory=$True)]
[string]
$ResourceGroupName,
[Parameter(Mandatory=$True)]
[string]
$WebAppName,
[Parameter(Mandatory=$True)]
[string]
$VirtualNetworkName,
[Parameter(Mandatory=$True)]
[string]
$SubnetName
)
Add-AzWebAppAccessRestrictionRule -ResourceGroupName $ResourceGroupName -WebAppName $WebAppName -Name "VPN" -Priority 500 -Action Allow -VirtualNetworkName "$VirtualNetworkName" -SubnetName "$SubnetName"
How can I reference Virtual Network that resides in other Resource Group than my Web Apps? Documentation don't seem to have such example. I'm able to reference Virtual Network in another Resource Group in Portal and via ARM Template, but when I use the PowerShell script mentioned above I get:
##[error]The Resource 'Microsoft.Network/virtualNetworks/vNet1' under resource group 'Test1-RG' was not found.

You could use the -SubnetId parameter to reference the subnet in another resource group.
The SubnetId is like
"/subscriptions/<subscriptiondID>/resourceGroups/<rgName>/providers/Microsoft.Network/virtualNetworks/<vnetName>/subnets/<subnetName>"
Param (
[Parameter(Mandatory=$True)]
[string]
$ResourceGroupName,
[Parameter(Mandatory=$True)]
[string]
$WebAppName,
[Parameter(Mandatory=$True)]
[string]
$SubnetId
)
Add-AzWebAppAccessRestrictionRule -ResourceGroupName $ResourceGroupName -WebAppName $WebAppName -Name "VPN" -Priority 500 -Action Allow -SubnetId $SubnetId

Related

Azure Monitoring Database performance

I need to compile the following information: "a scheduled report that shows the DB environment state. From free space to performance, failed jobs and anything else that can cause a DB not to function correctly."
I keep getting referred to the same learn.microsoft links but for some reason i just get progressively more confused.
Can someone please help me with a step by step instruction on how to achieve the above mentioned?
All our DBs are on Azure VMs.
I tried Chat GPT for the disk sizes and it gave me a Power Shell code. <
# Connect to your Azure account
Connect-AzAccount
# Get a list of all virtual machines in your subscription
$vms = Get-AzVM
# Loop through the list of virtual machines
foreach ($vm in $vms) {
# Get the details of each virtual machine
$vmName = $vm.Name
$vmSize = $vm.HardwareProfile.VmSize
# Get a list of all disks attached to the virtual machine
$disks = Get-AzDisk | Where-Object { $_.ManagedBy -eq $vm.Id }
# Loop through the list of disks
foreach ($disk in $disks) {
# Get the details of each disk
$diskName = $disk.Name
$diskSize = $disk.DiskSizeGB
$diskType = $disk.StorageAccountType
# Print the virtual machine, disk, and disk size information
Write-Output "VM Name: $vmName"
Write-Output "VM Size: $vmSize"
Write-Output "Disk Name: $diskName"
Write-Output "Disk Size: $diskSize GB"
Write-Output "Disk Type: $diskType"
Write-Output ""
}
}
\>
I could not get free space information or Database information this way.
Your script is working but you are retrieving information about the VMs, not about the SQL Server that is stored within the VMs.
You need to login into the SQL Server inside the VM and run the query that you want:
# Load the Azure RM module
Import-Module AzureRM
# Login to Azure
Login-AzureRmAccount
# Get a list of all Azure VMs
$vms = Get-AzureRmVM
# Loop through each VM
foreach ($vm in $vms) {
# Get the VM's IP address
$ipAddress = (Get-AzureRmPublicIpAddress -ResourceGroupName $vm.ResourceGroupName -Name ($vm.Name + '-ip')).IpAddress
# Connect to SQL Server on the VM
$connectionString = "Server=$ipAddress;Database=master;User ID=<username>;Password=<password>"
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$connection.Open()
# Execute the SELECT ##VERSION query
$command = $connection.CreateCommand()
$command.CommandText = "SELECT ##VERSION"
$reader = $command.ExecuteReader()
# Display the result
while ($reader.Read()) {
Write-Output $reader.GetValue(0)
}
# Close the connection
$connection.Close()
}
Note that you will need to replace <username> and <password> with the actual SQL Server login credentials for each VM.
Replace the "SELECT ##VERSION" with the query that investigates:
DB environment state
free space
performance
failed jobs
anything else...

virtual network service endpoint

I have a virtual network in my resource group with the default subnet Microsoft Storage Service endpoints are already assigned to the default subnet of the virtual network but, now I want to add another multiple service endpoint with default subnet using PowerShell
The code below is what I'm using to add the service endpoint Microsoft.ServiceBus to the same virtual network.
#Get vnet
$virtualnetwork = Get-AzureRmVirtualNetwork -Name $VN -ResourceGroupName $RG
#Configure service endpoint
Add-AzureRmVirtualNetworkSubnetConfig -Name $SN -AddressPrefix $SAP -
VirtualNetwork $virtualnetwork -ServiceEndpoint $EP
#Set configuration
$virtualnetwork | Set-AzureRmVirtualNetwork
The issue is that every time I run the above script, it updates the current service endpoint rather than adding a new one. Any idea
I tried to reproduce the same in my environment and added the service endpoint successfully like below.
I have created microsoft.storage service endpoint with default subnet like Below.
I tried to add another service endpointMicrosoft.ServiceBus to the same virtual network with default subnet using below powershell script
$subscription = "ID"
$subnets = #('default')
$vnetName = "your vnetname"
$vnetRgName = "Rgname"
$newEndpoint = "Microsoft.ServiceBus"
Set-AzContext -Subscription $subscription
foreach($snet in $subnets){
Write-Host "Modifying Service Endpoints for subnet: $snet" -fore red -back white
$virtualNetwork = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Get-AzVirtualNetworkSubnetConfig -Name $snet
$addrPrefix = $virtualNetwork.AddressPrefix
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$virtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
if ($ServiceEndPoint -notcontains $newEndPoint){
$ServiceEndPoint.Add($newEndpoint)
}
$delegation=$virtualNetwork.Delegations
#Add new service endpoint
Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Set-AzVirtualNetworkSubnetConfig -Name $snet -AddressPrefix $addrPrefix -ServiceEndpoint $ServiceEndPoint -Delegation $delegation | Set-AzVirtualNetwork
}
Output:
To check in portal, Microsoft.serviceBus is added successfully with default subnet along with Microsoft.storage.

Failed to setup Custom Domain for APIM using PowerShell script

I am trying to setup custom domain for my APIM instance using below script
[CmdletBinding()]
param (
[String]
$ResourceGroupName,
[String]
$Hostname,
[String]
$ApimServiceName,
[string]
$KeyVaultId
)
$ProxyHostnameConf = New-AzApiManagementCustomHostnameConfiguration -Hostname $Hostname -HostnameType "Proxy" -KeyVaultId $KeyVaultId -DefaultSslBinding
$apim = Get-AzApiManagement -ResourceGroupName $ResourceGroupName -Name $ApimServiceName
$apim.ProxyCustomHostnameConfiguration = $ProxyHostnameConf
Set-AzApiManagement -InputObject $apim
But the script is failing with below error
Line |
15 | Set-AzApiManagement -InputObject $apim
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| 'SubnetResourceId' does not match expected pattern
| '^/subscriptions/[^/]*/resourceGroups/[^/]*/providers/Microsoft.(ClassicNetwork|Network)/virtualNetworks/[^/]*/subnets/[^/]*$'.
I am getting this error both in my local machine as well as from the devops Microsoft hosted agent
I was able to fix this using azure cli command mentioned in the below ink
Azure CLI - Bash script to set up API Management custom domain
[CmdletBinding()]
param (
[String]
$ResourceGroupName,
[String]
$HostName,
[String]
$KeyVaultId,
[String]
$ApimServiceName
)
$config ='[{\"hostName\":\"'+$HostName+'\",\"type\":\"Proxy\",\"keyVaultId\":\"'+$KeyVaultId+'\",\"defaultSslBinding\":true,\"negotiateClientCertificate\":false}]'
Write-Host $config
az apim update --resource-group $ResourceGroupName --name $ApimServiceName --set hostnameConfigurations=$config

Az PowerShell CmdLet Get-AzDataLakeGen2ChildItem Proxy Authentication Error

I am running simple ps cmdlets to connect to azure datalake gen2 storage, some of the cmdlets are working and authenticating through corporate proxy (powershell is configured to use proxy on my machine). however some commands are failing with "Proxy Authentication is required".
Can someone share ideas or reason or fix ?
$subscription = "subscription"
$storageAccount = "storage"
$filesystem = "rawdata"
Connect-AzAccount -Subscription $subscription | Out-Null
$context = New-AzStorageContext -StorageAccountName $storageAccount -UseConnectedAccount
Below commands are throwing an error
Get-AzDataLakeGen2Item -Context $ctx -FileSystem $fileSystem
Get-AzDataLakeGen2ChildItem -Context $context -FileSystem $fileSystem
Get-AzDataLakeGen2ChildItem : Proxy Authentication Required At line:1
char:1
Get-AzDataLakeGen2ChildItem -Context $ctx
+ CategoryInfo : CloseError: (:) [Get-AzDataLakeGen2ChildItem], RequestFailedException
+ FullyQualifiedErrorId : RequestFailedException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.GetAzDataLakeGen2ChildItemCommand
But this command is working fine.
Get-AzDatalakeGen2FileSystem -Context $ctx
One of the workaround for connecting to the Azure Data Lake Gen2 Storage account using PowerShell through Proxy by using following Code:
$browser = New-Object System.Net.WebClient
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
Run this Code before connecting to the Azure Account.
I have executed this code to list the files available in the directory of my container in Azure Data Lake Gen2 Storage locally (Windows PowerShell ISE)
Windows PowerShell ISE:
Reference: Access web using PowerShell and Proxy

Access SQL - WMI Namespaces from Remote Machine

i am playing with Powershell and SQL WMI events and i am wondering if i can do this stuff remotely from the admin notebook:
I'd like to query the "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" namespace:
On SQLServer directly:
get-wmiobject -list -namespace "root\Microsoft\SqlServer" >> Works!
get-wmiobject -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" >> Works !
On my Adminmachine:
get-wmiobject -list -namespace "root\Microsoft\SqlServer" >> Works!
get-wmiobject -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" >> Error: Invalid Namespace.
Is there a trick to get this running? Do i have to additional install sth?
I am still on SQL 2005.
Thanks!
Use the computername name parameter.
get-wmiobject -computername Z002 -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER"
Also keep in mind MSSQLSERVER is only available if the server has a default instance. If the server uses a named instance you'll need to specify the instance name instead of MSSQLSERVER.
Posted - 05/05/2012 : 08:25:20
Hi All,
We've developed a free WMI CLR assembly to execute WMI queries in SQL.
e.g. This will return mount point and drive space
DECLARE #XmlData Xml
--Obtain Windows Services
select #XmlData=dbo.GetWMI('\\SQL2008WIN2008\root\cimv2', --Machine and WMI class
NULL, --UserName, leave NULL to use current
NULL, --Password, leave NULL to use current
'select * from win32_volume' --WMI Class
)
SELECT
tbl.A.value('(DeviceID)[1]','VARCHAR(100)') as DeviceID,
tbl.A.value('(Name)[1]','VARCHAR(200)') as Name,
tbl.A.value('(DriveType)[1]','int') as DriveType,
ISNULL(tbl.A.value('(DriveLetter)[1]','VARCHAR(10)'),'MountPoint') as DriveLetter,
tbl.A.value('(FreeSpace)[1]','bigint')/1024/1024 as FreeSpaceMbytes
FROM #XmlData.nodes('/WMI/Data') tbl(A)
Have a look at http://micatio.com/sqlwmi.aspx