PSUtilities.psm1

Function Update-LocalModules
{
<#
.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
.PARAMETER Scope
   Changes the Scope to the current user
 
#>

[CmdletBinding(DefaultParameterSetName='Admin')]
Param (
[Parameter(ParameterSetName='Admin')]
[switch]$RemoveOld,
[Parameter(ParameterSetName='User')]
[ValidateSet("CurrentUser")]
[string]$Scope
)

#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"}

#Checks Administrative privileges
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) -and ($PSCmdlet.ParameterSetName -eq'Admin'))
    {
    Write-Warning "You don't have administrative privileges. Run powershell.exe as an administrator, or run it into the scope of the current user:
    (-Remove parameter won't be available)
     
    `tUpdate-LocalModules -Scope CurrentUser"
 ;return
    }


$Startscript = Get-Date
Start-Transcript -Path .\UpdateModules$("{0:yyMMddHHmm}"-f (get-date)).log -Force

if ($PSCmdlet.ParameterSetName -eq 'user') {Write-Host "Running in the user context..." -ForeGroundColor Yellow}
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 ([version]$module.Version -lt [version]$OnlineModule.Version) {
    Write-Host "`nLocal version outdated, installing new online version... " -ForegroundColor Yellow -NoNewline
    Write-Host "$(($OnlineModule).Version) $($OnlineModule.name)" -ForegroundColor Green

    if ($PSCmdlet.ParameterSetName -eq 'user'){
    $Parameters= @{Scope=($PSBoundParameters["Scope"])}
    Install-Module -Name $OnlineModule.name -Force -AllowClobber @Parameters}

    else{Install-Module -Name $OnlineModule.name -Force -AllowClobber}
    $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 RDGFilePath
   FilePath for the destination RDG file
.EXAMPLE
   This creates a RDG file in custom path:
   Create-RDGFilefromActiveAZSubscription -RDGFilePath C:\temp\test.rdg
#>

Param([string]$RDGFilePath
)

if ((Get-AzureRmContext).Subscription.Name){
Write-Host "Current Azure context:$(Get-AzureRmContext | Out-String)" -ForegroundColor Yellow
}
else {
Write-Host "No Azure context found, use 'Login-AzureRmAccount' to connect or 'Select-AzureRmSubscription' to select a Subscription" -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={$_.IpConfigurations.Publicipaddress.Id}}, `
 @{N="LoadBalancerRule";E={$_.IpConfigurations.LoadBalancerBackendAddressPools.Id}}, `
 @{N="VMNetworkInterfaceid";E={$_.id}},@{N="VMid";E={($_.VirtualMachineText | ConvertFrom-Json).id}}

Write-Host "Getting info from Public IPS..." -ForegroundColor Cyan
$PublicIPs = Get-AzureRmPublicIpAddress| Select-Object -Property @{Name="PublicIPname";Expression={($_[0].DnsSettingsText | ConvertFrom-Json).fqdn}},@{Name="PublicIPAdress";Expression={$_.IpAddress}},@{Name="PublicIPid";Expression={$_.id}},@{Name="Associatedto";Expression={($_.IpConfigurationText | ConvertFrom-Json).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

$VMNetworkInterfacedata | Where-Object {$_.LoadBalancerRule} 
$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 VM... $($VMResource.Name) " -ForegroundColor Green -NoNewline
if ($VMResource.Properties.storageProfile.osDisk.osType -eq "windows")
{
Write-Host "Windows:added"
$rgarray += @{
Computername = $VMResource.Properties.osProfile.computerName
adminuser = $VMResource.Properties.osProfile.adminusername
PublicIPAdress = $PublicIPshash["$($_.PublicIPid)"].PublicIPadress
PublicIPName = $PublicIPshash["$($_.PublicIPid)"].PublicIPName
}
}
else {Write-Host "Linux:skipped" -ForegroundColor Red}

}
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 $RDGFilePath -Encoding utf8;$script:drgfile = Get-Item $RDGFilePath}
else{$RDGtext | Out-File -FilePath "$($azureSubscription).rdg" -Encoding utf8;$script: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 $drgfile}

}

Function test{

$ResourceGroupName = "grupode recursos"
$containerid = (New-Guid).Guid
$Parentid = (New-Guid).Guid

$container = [ordered]@{
Name                                     = $ResourceGroupName
Id                                       = $containerid
Parent                                   = $Parentid
NodeType                                 = "Container"
Description                              = ""
Icon                                     = "mRemoteNG"
Panel                                    = "General"
Username                                 = ""
Password                                 = ""
Domain                                   = ""
Hostname                                 = ""
Protocol                                 = "RDP"
PuttySession                             = "Default Settings"
Port                                     = "3389"
ConnectToConsole                         = 'False'
UseCredSsp                               = "True"
RenderingEngine                          = "IE"
ICAEncryptionStrength                    = "EncrBasic"
RDPAuthenticationLevel                   = "NoAuth"
LoadBalanceInfo                          = ""
Colors                                   = "Colors16Bit"
Resolution                               = "FitToWindow"
AutomaticResize                          = "True"
DisplayWallpaper                         = 'False'
DisplayThemes                            = 'False'
EnableFontSmoothing                      = 'False'
EnableDesktopComposition                 = 'False'
CacheBitmaps                             = 'False'
RedirectDiskDrives                       = 'False'
RedirectPorts                            = 'False'
RedirectPrinters                         = 'False'
RedirectSmartCards                       = 'False'
RedirectSound                            = "DoNotPlay"
RedirectKeys                             = 'False'
PreExtApp                                = ""
PostExtApp                               = ""
MacAddress                               = ""
UserField                                = ""
ExtApp                                   = ""
VNCCompression                           = "CompNone"
VNCEncoding                              = "EncHextile"
VNCAuthMode                              = "AuthVNC"
VNCProxyType                             = "ProxyNone"
VNCProxyIP                               = ""
VNCProxyPort                             = "0"
VNCProxyUsername                         = ""
VNCProxyPassword                         = ""
VNCColors                                = "ColNormal"
VNCSmartSizeMode                         = "SmartSAspect"
VNCViewOnly                              = 'False'
RDGatewayUsageMethod                     = "Never"
RDGatewayHostname                        = ""
RDGatewayUseConnectionCredentials        = "Yes"
RDGatewayUsername                        = ""
RDGatewayPassword                        = ""
RDGatewayDomain                          = ""
InheritCacheBitmaps                      = 'False'
InheritColors                            = 'False'
InheritDescription                       = 'False'
InheritDisplayThemes                     = 'False'
InheritDisplayWallpaper                  = 'False'
InheritEnableFontSmoothing               = 'False'
InheritEnableDesktopComposition          = 'False'
InheritDomain                            = 'False'
InheritIcon                              = 'False'
InheritPanel                             = 'False'
InheritPassword                          = 'False'
InheritPort                              = 'False'
InheritProtocol                          = 'False'
InheritPuttySession                      = 'False'
InheritRedirectDiskDrives                = 'False'
InheritRedirectKeys                      = 'False'
InheritRedirectPorts                     = 'False'
InheritRedirectPrinters                  = 'False'
InheritRedirectSmartCards                = 'False'
InheritRedirectSound                     = 'False'
InheritResolution                        = 'False'
InheritAutomaticResize                   = 'False'
InheritUseConsoleSession                 = 'False'
InheritUseCredSsp                        = 'False'
InheritRenderingEngine                   = 'False'
InheritUsername                          = 'False'
InheritICAEncryptionStrength             = 'False'
InheritRDPAuthenticationLevel            = 'False'
InheritLoadBalanceInfo                   = 'False'
InheritPreExtApp                         = 'False'
InheritPostExtApp                        = 'False'
InheritMacAddress                        = 'False'
InheritUserField                         = 'False'
InheritExtApp                            = 'False'
InheritVNCCompression                    = 'False'
InheritVNCEncoding                       = 'False'
InheritVNCAuthMode                       = 'False'
InheritVNCProxyType                      = 'False'
InheritVNCProxyIP                        = 'False'
InheritVNCProxyPort                      = 'False'
InheritVNCProxyUsername                  = 'False'
InheritVNCProxyPassword                  = 'False'
InheritVNCColors                         = 'False'
InheritVNCSmartSizeMode                  = 'False'
InheritVNCViewOnly                       = 'False'
InheritRDGatewayUsageMethod              = 'False'
InheritRDGatewayHostname                 = 'False'
InheritRDGatewayUseConnectionCredentials = 'False'
InheritRDGatewayUsername                 = 'False'
InheritRDGatewayPassword                 = 'False'
InheritRDGatewayDomain                   = 'False'
InheritRDPAlertIdleTimeout               = 'False'
InheritRDPMinutesToIdleTimeout           = 'False'
InheritSoundQuality                      = 'False'
}

$serverid = (New-Guid).Guid
$servertoconnectto = [ordered]@{
Name                                     = "STH-LINUX01"
Id                                       = $serverid
Parent                                   = $containerid
NodeType                                 = "Connection"
Description                              = ""
Icon                                     = "mRemoteNG"
Panel                                    = "General"
Username                                 = "aa-admin"
Password                                 = ""
Domain                                   = ""
Hostname                                 = "104.215.182.203"
Protocol                                 = "SSH2"
PuttySession                             = "Default Settings"
Port                                     = "22"
ConnectToConsole                         = 'False'
UseCredSsp                               = "True"
RenderingEngine                          = "IE"
ICAEncryptionStrength                    = "EncrBasic"
RDPAuthenticationLevel                   = "NoAuth"
LoadBalanceInfo                          = ""
Colors                                   = "Colors16Bit"
Resolution                               = "FitToWindow"
AutomaticResize                          = "True"
DisplayWallpaper                         = 'False'
DisplayThemes                            = 'False'
EnableFontSmoothing                      = 'False'
EnableDesktopComposition                 = 'False'
CacheBitmaps                             = 'False'
RedirectDiskDrives                       = 'False'
RedirectPorts                            = 'False'
RedirectPrinters                         = 'False'
RedirectSmartCards                       = 'False'
RedirectSound                            = "DoNotPlay"
RedirectKeys                             = 'False'
PreExtApp                                = ""
PostExtApp                               = ""
MacAddress                               = ""
UserField                                = ""
ExtApp                                   = ""
VNCCompression                           = "CompNone"
VNCEncoding                              = "EncHextile"
VNCAuthMode                              = "AuthVNC"
VNCProxyType                             = "ProxyNone"
VNCProxyIP                               = ""
VNCProxyPort                             = "0"
VNCProxyUsername                         = ""
VNCProxyPassword                         = ""
VNCColors                                = "ColNormal"
VNCSmartSizeMode                         = "SmartSAspect"
VNCViewOnly                              = 'False'
RDGatewayUsageMethod                     = "Never"
RDGatewayHostname                        = ""
RDGatewayUseConnectionCredentials        = "Yes"
RDGatewayUsername                        = ""
RDGatewayPassword                        = ""
RDGatewayDomain                          = ""
InheritCacheBitmaps                      = 'False'
InheritColors                            = 'False'
InheritDescription                       = 'False'
InheritDisplayThemes                     = 'False'
InheritDisplayWallpaper                  = 'False'
InheritEnableFontSmoothing               = 'False'
InheritEnableDesktopComposition          = 'False'
InheritDomain                            = 'False'
InheritIcon                              = 'False'
InheritPanel                             = 'False'
InheritPassword                          = 'False'
InheritPort                              = 'False'
InheritProtocol                          = 'False'
InheritPuttySession                      = 'False'
InheritRedirectDiskDrives                = 'False'
InheritRedirectKeys                      = 'False'
InheritRedirectPorts                     = 'False'
InheritRedirectPrinters                  = 'False'
InheritRedirectSmartCards                = 'False'
InheritRedirectSound                     = 'False'
InheritResolution                        = 'False'
InheritAutomaticResize                   = 'False'
InheritUseConsoleSession                 = 'False'
InheritUseCredSsp                        = 'False'
InheritRenderingEngine                   = 'False'
InheritUsername                          = 'False'
InheritICAEncryptionStrength             = 'False'
InheritRDPAuthenticationLevel            = 'False'
InheritLoadBalanceInfo                   = 'False'
InheritPreExtApp                         = 'False'
InheritPostExtApp                        = 'False'
InheritMacAddress                        = 'False'
InheritUserField                         = 'False'
InheritExtApp                            = 'False'
InheritVNCCompression                    = 'False'
InheritVNCEncoding                       = 'False'
InheritVNCAuthMode                       = 'False'
InheritVNCProxyType                      = 'False'
InheritVNCProxyIP                        = 'False'
InheritVNCProxyPort                      = 'False'
InheritVNCProxyUsername                  = 'False'
InheritVNCProxyPassword                  = 'False'
InheritVNCColors                         = 'False'
InheritVNCSmartSizeMode                  = 'False'
InheritVNCViewOnly                       = 'False'
InheritRDGatewayUsageMethod              = 'False'
InheritRDGatewayHostname                 = 'False'
InheritRDGatewayUseConnectionCredentials = 'False'
InheritRDGatewayUsername                 = 'False'
InheritRDGatewayPassword                 = 'False'
InheritRDGatewayDomain                   = 'False'
InheritRDPAlertIdleTimeout               = 'False'
InheritRDPMinutesToIdleTimeout           = 'False'
InheritSoundQuality                      = 'False'
}

$containerobject = [PSCustomobject]$container
$serverobject = [PSCustomobject]$servertoconnectto
$arrayservers =@()
$arrayservers += $serverobject

$containerobject |  ConvertTo-Csv -NoTypeInformation -Delimiter ";" | ForEach-Object {$_.Replace('"','')} | Out-File C:\tempRoche\TempRoche.csv -Append
$arrayservers | ForEach-Object { ConvertTo-Csv -InputObject $_ -NoTypeInformation -Delimiter ";"} | ForEach-Object {$_.Replace('"','')} | Select-Object -Skip 1 | Out-File C:\tempRoche\TempRoche.csv -Append

}


Export-ModuleMember -Function Update-LocalModules,Create-RDGFilefromActiveAZSubscription