PSUtilities.psm1
Function Update-LocalModules { Param ( [switch]$RemoveOld ) $Startscript = Get-Date Start-Transcript -Path .\UpdateModules$("{0:yyMMddHHmm}"-f (get-date)).log -Force <# .DESCRIPTION This Function updates local PowerShell modules with the last version online and deletes all the older local versions It registers all the activity in .\UpdateModules.log .PARAMETER RemoveOld This switch parameter removes the outdated local modules from disk #> #Checks Internet Conectivity if (-not( [Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet )){Throw "The machine needs to be connected to the internet"} Write-Host "Checking online modules..." $OnlineModules = Find-Module $CurrentFreespace = [math]::Round( (Get-Ciminstance -ClassName win32_logicaldisk | Where DeviceId -eq "C:").FreeSpace / 1mb,2) #Gets current latest module version installed Write-Host "Looking for Installed Modules..." -Foregroundcolor Green $Latest = Get-InstalledModule foreach ($module in $Latest) { #Local module is also online, shows the two versions if ($module.name -in ($OnlineModules).name) { $OnlineModule = $OnlineModules | where name -EQ $module.name Write-Host "`nOnline module: " -ForegroundColor Green -NoNewline Write-Host "$(($OnlineModule).Version) $($OnlineModule.name)" -ForegroundColor Green -NoNewline Write-Host " (Published on $("{0:dd/MM/yyyy}" -f $OnlineModule.PublishedDate) - $(((Get-Date) - $OnlineModule.PublishedDate).Days) Days ago)" -ForegroundColor Gray Write-Host "Local Module: " -ForegroundColor Gray -NoNewline write-host "$(($module).Version) $($module.name)" -ForegroundColor Gray -NoNewline if ($module.Version -lt $OnlineModule.Version) { Write-Host "`nLocal version outdated, installing new online version... " -ForegroundColor Yellow -NoNewline Write-Host "$(($OnlineModule).Version) $($OnlineModule.name)" -ForegroundColor Green Install-Module -Name $OnlineModule.name -Force $module.version = $OnlineModule.Version } else {Write-Host " Ok" -ForegroundColor White} } #Removes the older versions if parameter -RemoveOld has been specified if ($RemoveOld) { $Oldlocalmodules = Get-InstalledModule $module.Name -AllVersions | Where-Object {$_.Version -ne $module.Version} if ($Oldlocalmodules -ne $null) {Write-Host "Old modules found. Unninstalling older modules..." -ForegroundColor Gray; $Oldlocalmodules | Uninstall-Module -Force -Verbose } } } if ($RemoveOld) { $CleanedFreespace = [math]::Round( (Get-Ciminstance -ClassName win32_logicaldisk | Where DeviceId -eq "C:").FreeSpace / 1mb,2) $Freedspace = $CleanedFreespace - $CurrentFreespace Write-Host "`nFreed Space in C: $([math]::round($Freedspace,2)) MB" -ForegroundColor Green Write-Host "Current Space in C: $([math]::round($CleanedFreespace,2)) MB" -ForegroundColor Green } Write-Host "Time elapsed: $(((Get-Date) - $Startscript).Minutes) Minute(s)" -ForegroundColor Green Stop-Transcript } Function Create-RDGFilefromActiveAZSubscription {<# .DESCRIPTION This function creates a RDG file in the local folder Than contains all the VMs in the current Azure Subscription grouped by ResorceGroup. This file can be oppened with Remote Desktop Connection Manager 2.7 https://www.microsoft.com/en-us/download/details.aspx?id=44989 .PARAMETER FilePath FilePath for the destination RDG file .EXAMPLE This creates a RDG file is a coustom path: Create-RDGFilefromActiveAZSubscription -FilePath C:\temp\test.rdg #> Param([string]$FilePath ) if ($false){ Write-Host "Current Azure context:$(Get-AzureRmContext | Out-String)" -ForegroundColor Yellow } else { Write-Host "No Azure context found, use 'Login-AzureRmAccount' to connect" -ForegroundColor Red; break } Write-Host "Getting info from network interfaces..." -ForegroundColor Cyan $VMNetworkInterfaces = (Get-AzureRmResourceGroup).ResourceGroupName | ForEach-Object -Process { Write-Host "Reading from ResourceGroup ... $_" -ForegroundColor Green Get-AzureRmNetworkInterface -ResourceGroupName $_ | Where-Object -Property VirtualMachine -NE $null } Write-Host "Done." -ForegroundColor Green #Array of VMNetworkInterface information that contains Resource Group Name, PublicIPid, VMNetworkInterfaceid and VMid $VMNetworkInterfacedata = $VMNetworkInterfaces | Select-Object -Property @{N="ResourceGroupName";E={$_.ResourceGroupName}}, @{N="PublicIPid";E={($_.IpConfigurationsText | ConvertFrom-Json).PublicIpAddress.id}}, @{N="VMNetworkInterfaceid";E={$_.id}},@{N="VMid";E={($_.VirtualMachineText | ConvertFrom-Json).id}} Write-Host "Getting info from Public IPS..." -ForegroundColor Cyan $PublicIPs = Get-AzureRmPublicIpAddress $PublicIPs = Get-AzureRmPublicIpAddress| Select-Object -Property @{Name="PublicIPname";Expression={($_[0].DnsSettingsText | ConvertFrom-Json).fqdn}},@{Name="PublicIPAdress";Expression={$_.IpAddress}},@{Name="PublicIPid";Expression={$_.id}} $PublicIPshash = $PublicIPs | Group-Object -Property PublicIPid -AsHashTable -AsString # hashtable with PublicIPid, PublicIPAdress and PublicIPName Write-Host "Done." -ForegroundColor Green # Wraping it all.. Write-Host "Getting info from VMs..." -ForegroundColor Cyan $rgdata = @() foreach ($RGroupName in ($VMNetworkInterfacedata | Group-Object -Property ResourceGroupName)) { $obj = New-Object -TypeName PScustomobject Add-Member -InputObject $obj -MemberType NoteProperty -Name ResourceGroupName -Value $RGroupName.Name $rgarray= @() $RGroupName.group | ForEach-Object -Process { $VMResource = Get-AzureRmResource -ResourceId $_.vmid # Gets VM Azure Resource Write-Host "Reading from ResourceGroup ... $($RGroupName.Name)" -ForegroundColor Green $rgarray += @{ Computername = $VMResource.Properties.osProfile.computerName adminuser = $VMResource.Properties.osProfile.adminusername PublicIPAdress = $PublicIPshash["$($_.PublicIPid)"].PublicIPAdress PublicIPName = $PublicIPshash["$($_.PublicIPid)"].PublicIPName } } Add-Member -InputObject $obj -MemberType NoteProperty -Name Resources -Value $rgarray $rgdata += $obj } Write-Host "Done." -ForegroundColor Green $rgdata | Out-String #region RDG file Creation $RDGtext ="" #Writes Header $azureSubscription = (Get-AzureRmContext).Subscription.Name $commonuser ="user" $main = @" <?xml version="1.0" encoding="utf-8"?> <RDCMan programVersion="2.7" schemaVersion="3"> <file> <credentialsProfiles /> <properties> <expanded>True</expanded> <name>$azureSubscription</name> </properties> <logonCredentials inherit="None"> <profileName scope="Local">Custom</profileName> <userName>$commonuser</userName> <password /> <domain>EUROPE</domain> </logonCredentials> <remoteDesktop inherit="None"> <sameSizeAsClientArea>True</sameSizeAsClientArea> <fullScreen>False</fullScreen> <colorDepth>24</colorDepth> </remoteDesktop> "@ $RDGtext += $main #Writes Groups (one for each RG) foreach ($rg in $rgdata) { $RGroupName = $rg.ResourceGroupName $grupo = @" <group> <properties> <expanded>True</expanded> <name>$RGroupName</name> </properties> "@ $RDGtext +=$grupo #Writes Servers for each RG foreach ($VM in $rg.Resources) { if ($VM["PublicIPName"] -ne $null){$PublicIPAdress=$VM["PublicIPName"]} else {$PublicIPAdress=$VM["PublicIPAdress"]} $server = @" <server> <properties> <displayName>$($VM["Computername"])</displayName> <name>$PublicIPAdress</name> </properties> "@ $RDGtext +=$server $logon = @" <logonCredentials inherit="None"> <profileName scope="Local">Custom</profileName> <userName>$($VM["adminuser"])</userName> <password></password> <domain /> </logonCredentials> "@ $RDGtext +=$logon $endserver = @" </server> "@ $RDGtext += $endserver } $endgrupo = @" </group> "@ $RDGtext +=$endgrupo } #Writes Footer $endmain = @" </file> <connected /> <favorites /> <recentlyUsed /> </RDCMan> "@ $RDGtext += $endmain #Outputs results to RDG file if ($PSBoundParameters.ContainsKey("FilePath")){$RDGtext | Out-File -FilePath $FilePath -Encoding utf8;$drgfile = Get-Item $FilePath} else{$RDGtext | Out-File -FilePath "$($azureSubscription).rdg" -Encoding utf8;$drgfile = Get-Item "$($azureSubscription).rdg" } Write-Host "RDG file generated:" -ForegroundColor Cyan Write-Host "$drgfile" -ForegroundColor White #endregion $option = "N" $option = Read-Host "Do you want to open it (Y/N)" if ($option -eq "y") {Invoke-Item $FilePath} } Export-ModuleMember -Function Update-LocalModules,Create-RDGFilefromActiveAZSubscription |