Welcome to Sexy Snippets!

A place to find lots of awesome code snippets (mainly PowerShell)

Jump to snippet

Get-ChildItem find hidden files in music folders
Flatten folders to one child directory
vSphere PowerCli
Azure PowerShell


$files = Get-ChildItem -file -recurse (use -force to get hidden files)
$files | Where-Object {$_.name -like "*.db"} | remove-item -whatif
$files | Where-Object {$_.name -like "*.db"} | remove-item -confirm -force
$files | Where-Object {$_.name -like "*.jpg"} | remove-item -confirm -force
$files | Where-Object {$_.name -like "*.jpeg"} | remove-item -confirm -force
$files | Where-Object {$_.name -like "*.ini"} | remove-item -confirm -force


$targetDir = Convert-Path '.' # Get the current (target) directory's full path.

$mp3Files = Get-ChildItem -Recurse -File -Filter *.mp3 # Loop over all *.mp3 files in subtrees of child dirs.

Foreach ($file in $mp3files) {
$destination = Join-Path $targetdir ($file.FullName.Substring($targetDir.Length) -replace '(.*?)\\(.*)', '$1 - $2')
$destination -match '(.*?)\\(.*?)\\'
$newDir = $targetdir + $matches[2]
if (!(Test-Path -path $newDir)) {New-Item $newDir -Type Directory}
Move-Item $file.FullName -Destination $destination
}


# Find VMs with snapshots
$VMsWithSnapshots = @(Get-VM | Get-Snapshot | Select vm,name,created,description,@{N="SizeGB";E={[math]::round($_.SizeGB,2)}}) | Sort-Object Created

# Cold Snapshot VMs that match a pattern
$VMs = Get-VM webserver*2*dev
$VMs | ForEach-Object {Shutdown-VMGuest -VM $_ -Confirm:$false}
$VMs | ForEach-Object {New-Snapshot -VM $_ -Name "Before Octopus deploy" -Description "Change Request #123" -Confirm:$false}
$VMs | ForEach-Object {Start-VM -VM $_ -Confirm:$false}

# Find VMs with no tags
$VMsnoTags = Get-VM | Where-Object {(Get-TagAssignment $_) -eq $null}


# Add tags to Azure Arc Machines from properly formatted CSV e.g.:
# VM		BusinessUnit		OwnerTeam	Environment
# SERVER1	Digital Services	Web			prod
# SERVER2	Digital Services	Web			dev
# SERVER3	Digital Services	Web			test
# SERVER4	Digital Services	Web			uat

$AzureArcServers = Import-Csv C:\Temp\AzureArcServers.csv

foreach ($row in $AzureArcServers){
        
    $vm = Get-AzResource -Name $row.VM -ResourceType Microsoft.HybridCompute/machines

    if ($vm -ne $null){
		$AZTags = @{BusinessUnit = $row.BusinessUnit.ToString(); OwnerTeam = $row.OwnerTeam.ToString(); Environment = $row.Environment.ToString()}

		Write-Host
		Write-Host "Updating Azure Arc VM " -ForegroundColor Green -NoNewline
		Write-Host $vm.Name -ForegroundColor Yellow -NoNewline
		Write-Host " with the following tags: " -ForegroundColor Green
		$AZTags | Out-String | ForEach-Object { Write-Host -NoNewline $_ }
			
		Update-AzTag -ResourceId $vm.Id -Tag $AZTags -Operation Merge
		
		Clear-Variable vm
		Clear-Variable AZTags
       
    }
    else {
        Write-Host "No VM found named $($item.VM)!"
    }
}