Friday, November 20, 2026

Clone Azure VM using Bicep

 <#

Creates a new Azure VM using configuration discovered from an existing VM.
.DESCRIPTION
Recreates the source VM's size, Marketplace image reference, OS disk size/SKU,
subnet, NIC NSG (when attached at NIC level), accelerated networking, and
security type settings. Data disks are reported but not recreated in this version.
This does NOT copy the source VM's OS, files, installed software, data disk contents,
data disk contents, public IP, private IP, extensions, tags, or VM identity.
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory)] [string] $SourceVM,
    [Parameter(Mandatory)] [string] $SourceResourceGroup,
    [Parameter(Mandatory)] [string] $NewVM,
    [Parameter(Mandatory)] [string] $TargetResourceGroup,
    [string] $TemplateFile = (Join-Path $PSScriptRoot 'clone-vm.bicep'),
    [string] $TargetLocation,
    [string] $TargetSubnetId,
    [switch] $SkipDataDisks,
    [switch] $SkipNicNsg,
    [switch] $DisableBootDiagnostics
)

$ErrorActionPreference = 'Stop'


function Get-DiskSkuName {
    param($Disk)
    if ($Disk.Sku -and $Disk.Sku.Name) { return [string]$Disk.Sku.Name }
    return 'Standard_LRS'
}

function Get-ResourceGroupAndNameFromId {
    param([Parameter(Mandatory)][string]$ResourceId)
    $parts = $ResourceId.TrimEnd('/') -split '/'
    $rgIndex = [Array]::IndexOf($parts, 'resourceGroups')
    if ($rgIndex -lt 0 -or ($rgIndex + 1) -ge $parts.Length) {
        throw "Unable to parse resource group from resource ID: $ResourceId"
    }
    return @{ ResourceGroupName = $parts[$rgIndex + 1]; Name = $parts[-1] }
}


Write-Host "Checking Az modules and Azure login..." -ForegroundColor Cyan
if (-not (Get-Command Get-AzVM -ErrorAction SilentlyContinue)) {
    throw "Az.Compute is not installed. Install with: Install-Module Az.Compute -Scope CurrentUser"
}
if (-not (Get-AzContext -ErrorAction SilentlyContinue)) {
    Connect-AzAccount | Out-Null
}


Write-Host "Reading source VM configuration..." -ForegroundColor Cyan
$source = Get-AzVM -ResourceGroupName $SourceResourceGroup -Name $SourceVM
$sourceOsDiskId = $source.StorageProfile.OsDisk.ManagedDisk.Id
if (-not $source.StorageProfile.ImageReference -or -not $source.StorageProfile.ImageReference.Publisher) {
    throw "The source VM does not expose a Marketplace image reference. This script creates a clean VM from an image; custom-image/specialized-disk VMs need a different approach."
}
$imageRef = @{
    publisher = [string]$source.StorageProfile.ImageReference.Publisher
    offer = [string]$source.StorageProfile.ImageReference.Offer
    sku = [string]$source.StorageProfile.ImageReference.Sku
    version = [string]$source.StorageProfile.ImageReference.Version
}
$sourceOsType = [string]$source.StorageProfile.OsDisk.OsType
if (-not $sourceOsType) { $sourceOsType = 'Windows' }
$osDiskParts = Get-ResourceGroupAndNameFromId -ResourceId $sourceOsDiskId
$osDisk = Get-AzDisk -ResourceGroupName $osDiskParts.ResourceGroupName -DiskName $osDiskParts.Name
$osDiskConfig = @{
    diskSizeGB = [int]$osDisk.DiskSizeGB
    sku = (Get-DiskSkuName $osDisk)
}

# NIC/subnet and NIC-level NSG discovery. Uses first primary NIC and first IP config.
$sourceNicId = $source.NetworkProfile.NetworkInterfaces[0].Id
$sourceNicParts = Get-ResourceGroupAndNameFromId -ResourceId $sourceNicId
$sourceNic = Get-AzNetworkInterface -ResourceGroupName $sourceNicParts.ResourceGroupName -Name $sourceNicParts.Name
$sourceIpConfig = $sourceNic.IpConfigurations | Select-Object -First 1
if (-not $TargetSubnetId) { $TargetSubnetId = $sourceIpConfig.Subnet.Id }
if (-not $TargetSubnetId) { throw 'Could not determine source subnet. Supply -TargetSubnetId.' }
$nicNsgId = ''
if (-not $SkipNicNsg -and $sourceNic.NetworkSecurityGroup) { $nicNsgId = $sourceNic.NetworkSecurityGroup.Id }
$accelerated = [bool]$sourceNic.EnableAcceleratedNetworking

# Recreate security profile when source VM is Trusted Launch or has a security type set.
$security = @{}
if ($source.SecurityProfile) {
    if ($source.SecurityProfile.SecurityType) { $security.securityType = [string]$source.SecurityProfile.SecurityType }
    if ($source.SecurityProfile.UefiSettings) {
        $security.uefiSettings = @{}
        if ($null -ne $source.SecurityProfile.UefiSettings.SecureBootEnabled) { $security.uefiSettings.secureBootEnabled = [bool]$source.SecurityProfile.UefiSettings.SecureBootEnabled }
        if ($null -ne $source.SecurityProfile.UefiSettings.VtpmEnabled) { $security.uefiSettings.vTpmEnabled = [bool]$source.SecurityProfile.UefiSettings.VtpmEnabled }
    }
}

# Data disks are intentionally not recreated by this template version.
if ($source.StorageProfile.DataDisks.Count -gt 0) {
    Write-Warning "Source VM has $($source.StorageProfile.DataDisks.Count) data disk(s). This version does not create or attach data disks."
}

$deployLocation = if ($TargetLocation) { $TargetLocation } else { $source.Location }
$vmSize = [string]$source.HardwareProfile.VmSize

$adminUser = Read-Host "Enter local admin username for new VM"
$adminPass = Read-Host "Enter local admin password for new VM" -AsSecureString
#$cred = [pscredential]::new($adminUser, $adminPass)
#$adminPasswordPlain = $cred.GetNetworkCredential().Password

$adminPasswordPlain = [System.Net.NetworkCredential]::new("", $adminPass).Password

if (-not (Test-Path $TemplateFile)) { throw "Bicep template not found: $TemplateFile" }
if (-not (Get-Command New-AzResourceGroupDeployment -ErrorAction SilentlyContinue)) {
    throw "Az.Resources is required. Install with: Install-Module Az.Resources -Scope CurrentUser"
}
if (-not (Get-Command bicep -ErrorAction SilentlyContinue)) {
    throw "Standalone Bicep CLI is required to avoid the embedded Bicep compiler crash. Install it from https://aka.ms/bicep-install and retry."
}

# Compile Bicep to ARM JSON with the standalone CLI, then deploy the JSON. This
# avoids the embedded Bicep compilation path used by some Az.Resources versions.
$tempArmTemplate = Join-Path $env:TEMP ("clone-$NewVM-$([guid]::NewGuid().ToString('N')).json")
try {
    Write-Host "Compiling Bicep template with standalone Bicep CLI..." -ForegroundColor Cyan
    & bicep build $TemplateFile --outfile $tempArmTemplate
    if ($LASTEXITCODE -ne 0 -or -not (Test-Path $tempArmTemplate)) {
        throw "Bicep compilation failed. Run 'bicep build $TemplateFile' to view diagnostics."
    }

    Write-Host "Deploying new VM '$NewVM' to resource group '$TargetResourceGroup'..." -ForegroundColor Cyan
    $deployment = New-AzResourceGroupDeployment `
    -ResourceGroupName $TargetResourceGroup `
    -Name "clone-$NewVM" `
    -TemplateFile $tempArmTemplate `
    -vmName $NewVM `
    -location $deployLocation `
    -vmSize $vmSize `
    -subnetId $TargetSubnetId `
    -imageReference $imageRef `
    -osType $sourceOsType `
    -osDiskConfig $osDiskConfig `
    -networkSecurityGroupId $nicNsgId `
    -enableAcceleratedNetworking $accelerated `
    -securityProfile $security `
    -adminUsername $adminUser `
    -adminPassword (ConvertTo-SecureString -String $adminPasswordPlain -AsPlainText -Force) `
} finally {
    if (Test-Path $tempArmTemplate) { Remove-Item $tempArmTemplate -Force -ErrorAction SilentlyContinue }
}

$adminPasswordPlain = $null
Write-Host "Deployment complete." -ForegroundColor Green
Write-Host "VM: $NewVM"
Write-Host "Location: $deployLocation"
Write-Host "VM size: $vmSize"
Write-Host "OS: $sourceOsType"
Write-Host "Image: $($imageRef.publisher)/$($imageRef.offer)/$($imageRef.sku):$($imageRef.version)"
if ($deployment.Outputs.vmId.Value) { Write-Host "VM ID: $($deployment.Outputs.vmId.Value)" }
Write-Warning "Data disks (if any) were created EMPTY. OS installation/software, data, extensions, public IP, original private IP, tags, and identity were not copied. Verify subnet/NSG/security settings before starting workloads."


Thursday, April 30, 2026

How to run a command on boot or startup in Ubuntu.


https://linuxvox.com/blog/automatically-run-a-program-on-startup-under-linux-ubuntu/

We start by creating a .sh file in /usr/bin/mycommand.sh
 
Enter the following text in it.

#!/bin/sh
sudo ip  route add 10.30.24.0/24 via  192.168.0.1 dev eth0 onlink

Creating a new service:
sudo nano /etc/systemd/system/mycommand.service # create new service file

Enter the following text in it.

[Unit]
Description=Add route command
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/bash /usr/bin/mycommand.sh
User=root #running as root user
Restart=never # do not restart the service if it fails

[Install]
WantedBy=multi-user.target

Starting the service:
sudo systemctl daemon-reload # reload the system daemon
sudo systemctl start mycommand.service # to start without rebooting for testing
sudo systemctl status mycommand.service # to verify status of service.
sudo systemctl enable mycommand.service # enable the service to run at startup


Removing a systemdservice
Sudo systemctl stop mycommand.service # stop the service
Sudo systemctl disable mycommand.service # disable the service
Sudo rm /ect/systemd/system/mycommand.service

 

 

Tuesday, March 4, 2025

SQL SPN Powershell Commands

List User Account Spn:

 Get-ADUSer -Filter { ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName | select 

SamAccountName, ServicePrincipalName

 

List Computer Account Spn
Get-ADComputer -Filter { ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName | select SamAccountName, ServicePrincipalName | Out-String -Width 4096 

Setting SPN:


setSPN -A MSSQLsvc/sqlserver1.contoso.com:59302 contoso\serviceaccount

setSPN -A MSSQLsvc/sqlserver1:59302 contoso\serviceaccount


 

Tuesday, November 26, 2024

SQL error when connecting to server using servername\instance.

SQL error when connecting to server using servername\instance. 

Error:

A network-related or instance-specific error occurred when establishing a connection to SQL server. the server was not found or was not accessible.Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error:26 - Error Locating Server/Instance Specified) (Microsoft SQL Server)

 


 Solution:

The UDP port 1434  on destination server was being  blocked in  the firewall.