BeHub.psm1


# use this file to define global variables on module scope
# or perform other initialization procedures.
# this file will not be touched when new functions are exported to
# this module.


#Azure
$global:AzResGrpName_StorageBlob = 'BePowerShell'
$global:AzStorageAccountName = "bepowershellfilestorage0"

#local
$global:BePowershellLocalPath = "$env:USERPROFILE\Documents\BePowerShell\"
function Update-BePowerShellContent {
  <#
      .SYNOPSIS
      First Testfunction
     
      .DESCRIPTION
      Mit dieser Funktion werden die Daten von BePowershell geholt. Hierbei wird ein Merge ausgef�hrt.
      Es ist zwingend notwendig das ein Azure-Account f�r den Datenspeicher verwendet wird.
     
      .INPUTS
      String
      String
     
      .OUTPUTS
      None
     
      .EXAMPLE
      Get-BePowerShellContent
     
      Ausgabe
      Ausgabe
 
      .EXAMPLE
      Get-BePowerShellContent
 
      Ausgabe
      Ausgabe
 
      .NOTES
     
  #>

  [CmdletBinding()]

  param(
    #Pfad zum Speicherort f�r die abzulegenden Daten
    [Parameter(Mandatory = $false)]
    $Path = $BePowershellLocalPath,
    #Containername aus welchem Quelldateien kopiert werden
    [Parameter(Mandatory = $false)]
    [string]$BlobContainerName = 'master',
    #Dieser Schalter erzwingt die neueingabe von Benutzerdaten bei der Anmeldung an Azure
    [Parameter(Mandatory = $false)]
    [switch]$ForceConnection,
    #Dieser Schalter deaktviert das automatische Eintragen des Download-Ziels in $env:PsModulePath
    [Parameter(Mandatory = $false)]
    [switch]$NoProfileModification,
    #Mit diesem Parameter lassen sich einzelne Dateien aus einem Blob-Storage-Container herunterladen (anstatt des gesamten Containers)
    [Parameter(Mandatory = $false)]
    [string[]]$FileName,
    #switch for system wide installation
    [Parameter(Mandatory = $false)]
    [switch]$ToSystem
  )

  Begin {
    if (!(get-module Az.Storage -ListAvailable))
    { Start-Process PowerShell.exe -Verb runas -ArgumentList '-Command "& { Install-Module Az -AllowClobber -Force -Verbose ; Write-Host done ; Start-Sleep -Seconds 5 ; exit }"' -Wait }

    if (!$ToSystem)
    { $PsPath = $Path.TrimEnd("\") }
    else 
    { $PsPath = "$env:windir\System32\WindowsPowershell\v1.0\Modules\" }
  }
  
  Process {
    if (!$ConnectionAzAccount -or $ForceConnection) {
      if (!$AzTenantId_BeTerna -or !$AzSubscriptionId_BeTerna) {
        if (Get-Module -ListAvailable BeAzure -ErrorAction SilentlyContinue) {
          Import-Module BeAzure -DisableNameChecking -WarningAction SilentlyContinue
          $global:AzTenantId_BeTerna = $AzureEnvironment["be-terna"].TenantId
          $global:AzSubscriptionId_BeTerna = $AzureEnvironment["be-terna"].SubscriptionId
        }
        else {
          $global:AzTenantId_BeTerna = Read-Host -Prompt "enter BE-terna Azure Tenant ID"
          $global:AzSubscriptionId_BeTerna = Read-Host -Prompt "enter BE-terna Azure Subscription ID"
        } 
      }
      $global:ConnectionAzAccount = Connect-AzAccount -TenantId $global:AzTenantId_BeTerna -Subscription $global:AzSubscriptionId_BeTerna
    }

    if ($ConnectionAzAccount) {
      $StorageAcc = Get-AzStorageAccount -ResourceGroupName $global:AzResGrpName_StorageBlob -Name $global:AzStorageAccountName 
      $StorageContext = $StorageAcc.Context 
      $StorageContainer = Get-AzStorageContainer -Context $StorageContext | Where-Object -FilterScript { $_.Name -eq $BlobContainerName }
      $Blobs = Get-AzStorageBlob -Container $StorageContainer.Name -Context $StorageContext
    
      if ($Blobs -and !$ToSystem)
      { $null = Remove-Item $PsPath -Recurse -Force }

      foreach ($Blob in $Blobs) {
        $DestPath = Join-Path -Path $PsPath -ChildPath ($Blob.Name)
        $null = New-Item ($DestPath) -ItemType File -Force
        
        if ($FileName) {
          if ($FileName -contains (($Blob.Name.split("/")[-1])))
          { Get-AzStorageBlobContent -Blob $Blob.Name -Container $StorageContainer.Name -Context $StorageContext -Destination $DestPath -Force }
          else
          { continue }
        }
        else
        { Get-AzStorageBlobContent -Blob $Blob.Name -Container $StorageContainer.Name -Context $StorageContext -Destination $DestPath -Force }
      }

      if (!$NoProfileModification) {
        $ModulePaths = $env:PSModulePath.split(';')
        if ($ModulePaths -notcontains $PsPath -and !$ToSystem) {         
          $Command = {
            $PsPath = $args[0]

            $originalpaths = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PSModulePath).PSModulePath
            $newPath = ($originalpaths + ';' + $PsPath)
            Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PSModulePath -Value $newPath
          }
        
          Start-Process powershell -verb runas -ArgumentList (' -Command "& {' + $Command + '}" '), $PsPath
        }
      }  
    }
  }  

  End {
    Write-Output -InputObject $PsPath
    Get-Module BeHub | Where-Object { $_.Path -ne "$env:USERPROFILE\Documents\BePowerShell\BeHub\loader.psm1" } | Uninstall-Module -Force -ErrorAction SilentlyContinue
  }
}