dimanche 21 mars 2010

Une console Powershell tout en un !

L'administration en ligne de commande c'est bien ! Mais quand cela nécessite plusieurs consoles c'est beaucoup moins amusant. Après avoir installé les outils de management de Exchange 2007 (EMS entre autre) sur mon poste client XP, j'ai vite trouvé un intérêt a l'agrémenter d'autres fonctionnalités comme la gestion de Active Directory avec le powershell (outils de chez Quest Software). Malheureusement après installation du package Quest ActiveRoles pour gérer l'active directory avec powershell, je me retrouve avec deux consoles distinctes. Le but est de les "fusionnées".


  1. Pré-requis
    Avoir installé les outils d'administration Exchange 2007 ainsi que le package Active Directory de Quest Software DISPO ICI (necessite Le .NET Framework 3.5SP1)

  2. Exemple de raccourci vers une console Powershell
    %SystemRoot%\system32\Windows\PowerShell\v1.0\powershell.exe -psconsolefile "C:\MesConsolePosh\UneConsole.psc1"

  3. Contenu du fichier .psc1 et modification.
    Il suffit tout simplement de créer un fichier .psc1 qui regroupe tous les autres fichiers consoles comme celui de Exchange, ActiveRoles, VmWare, etc...
    Exemple de fichier intégrant Exchange et ActiveRole :




    <?xml version="1.0" encoding="utf-8"?>
    <PSConsoleFile ConsoleSchemaVersion="1.0">
    <PSVersion>1.0</PSVersion>
    <PSSnapIns>
    <PSSnapIn Name="Microsoft.Exchange.Management.PowerShell.Admin" />
    <PSSnapIn Name="Quest.ActiveRoles.ADManagement" />
    </PSSnapIns>
    </PSConsoleFile>
    Il est maintenant possible dans une seule et même invite de commande d'exécuter des cmdlets Exchange 2007 et ActiveRoles.

  4. Personnalisation et finalisation.
    Lors du lancement de la console il est possible de spécifier un fichier de commande. Celui-ci peut permettre par exemple de définir des alias de commande. Voici un exemple de fichier dérivé de celui de Exchange 2007.






    ## ALIASES ###################################################################
    set-alias list       format-list
    set-alias table      format-table
    ## Confirmation is enabled by default, uncommenting next line will disable it
    # $ConfirmPreference = "None"
    ## EXCHANGE VARIABLEs ########################################################
    $global:exbin = (get-itemproperty HKLM:\SOFTWARE\Microsoft\Exchange\Setup).MsiInstallPath + "bin\"
    $global:exinstall = (get-itemproperty HKLM:\SOFTWARE\Microsoft\Exchange\Setup).MsiInstallPath
    $global:exscripts = (get-itemproperty HKLM:\SOFTWARE\Microsoft\Exchange\Setup).MsiInstallPath + "scripts\"
    $global:AdminSessionADSettings = [Microsoft.Exchange.Data.Directory.AdminSessionADSettings]::Instance
    ## Reset the Default Domain
    $global:AdminSessionADSettings.ViewEntireForest = $false
    $FormatEnumerationLimit = 16

    ## PROMPT ####################################################################

    ## PowerShell can support very rich prompts, this simple one prints the current
    ## working directory and updates the console window title to show the machine
    ## name and directory.

    function prompt{
    $cwd = (get-location).Path
    $scope = "View Entire Forest"
    if (!$AdminSessionADSettings.ViewEntireForest){
    $scope = $AdminSessionADSettings.DefaultScope
    }
    $host.UI.RawUI.WindowTitle = "Machine: " + $(hostname) + " | Scope: " + $scope + " | By Alexandre Létard"
    $host.UI.Write("Yellow", $host.UI.RawUI.BackGroundColor, "[Alex's POSH]")
    " $cwd>"
    }

    ## FUNCTIONs #################################################################
     ## returns all defined functions
     function functions{
        if ( $args )    {
            foreach($functionName in $args )        {
                 get-childitem function:$functionName |
                      foreach { "function " + $_.Name; "{" ; $_.Definition; "}" }
            }
        }
        else    {
            get-childitem function: |
                 foreach { "function " + $_.Name; "{" ; $_.Definition; "}" }
        }
    }
    ## generates a tip of the day
    function get-tip{
        param($local:number=$null)

        if( ($global:exrandom -eq $null) -or ($exrandom -isnot [System.Random]))    {
            $global:exrandom = new-object System.Random
        }

        $culture = [System.Threading.Thread]::CurrentThread.CurrentUICulture.Parent

        if ( test-path "$($global:exbin)\$($culture.Name)\extips.xml" )    {
    $culture = $culture.Name
        }
        else    {
    $culture = 'en'
        }

        if (test-path "$($global:exbin)\$culture\extips.xml")    {
             $local:tips = [xml](get-content $global:exbin\$culture\extips.xml)
            if($local:number -eq $null)       {
                $local:temp = $global:exrandom.Next( 0, $local:tips.topic.developerConceptualDocument.introduction.table.row.Count )
                write-host -fore Yellow ( "Tip of the day #" + $local:temp + ":`n" )
                $local:nav = $tips.topic.developerConceptualDocument.introduction.table.row[$local:temp].entry.CreateNavigator()
                [void] $nav.MoveToFirstChild()
                do            {
                   write-host $nav.Value
                }
                while( $nav.MoveToNext() )
       ""
            }
            else        {
                $local:nav = $tips.topic.developerConceptualDocument.introduction.table.row[$local:number].entry.CreateNavigator()    
       write-host -fore Yellow ( "Tip of the day #" + $local:number + ":`n" )
          
     
                [void] $nav.MoveToFirstChild()
                do            {
                     write-host $nav.Value
                }
                while( $nav.MoveToNext() )
                ""
            }
        }
        else    {
            "Exchange tips file $($global:exbin)\$culture\extips.xml not found!"
        }

        trap    {
    continue
        }
    }


    ## only returns exchange commands

    function get-excommand{
    if ($args[0] -eq $null) {
    get-command -pssnapin Microsoft.Exchange*
    }
    else {
    get-command $args[0] | where { $_.psSnapin -ilike 'Microsoft.Exchange*' }
    }
    }

    ## only returns activerole commands

    function get-adcommand{
    if ($args[0] -eq $null) {
    get-command -pssnapin Quest.ActiveRoles*
    }
    else {
    get-command $args[0] | where { $_.psSnapin -ilike 'Quest.ActiveRoles*' }
    }
    }

    ## only returns PowerShell commands

    function get-pscommand{
    if ($args[0] -eq $null) {
    get-command -pssnapin Microsoft.PowerShell*
    }
    else {
    get-command $args[0] | where { $_.PsSnapin -ilike 'Microsoft.PowerShell*' }
    }
    }
    ## prints the Exchange Banner in pretty colors
    function get-exbanner{
    write-host -foregroundcolor RED "`n         Welcome to the Alex's Management Shell!`n"

    write-host " Full list of cmdlets:          " -no
    write-host -fore Yellow "get-command"

    write-host " Only ActiveRole cmdlets:         " -no
    write-host -fore Yellow "get-excommand"

    write-host " Only Exchange cmdlets:         " -no
    write-host -fore Yellow "get-excommand"

    ## write-host " Only Monad cmdlets:            " -no
    ## write-host -fore Yellow "get-pscommand"

    write-host " Cmdlets for a specific role:   " -no
    write-host -fore Yellow "get-help -role *UM* or *Mailbox*"

    write-host " Get general help:              " -no
    write-host -fore Yellow "help"

    write-host " Get help for a cmdlet:         " -no
    write-host -fore Yellow "help <cmdlet-name> or <cmdlet-name> -?"

    write-host " Show quick reference guide:    " -no
    write-host -fore Yellow "quickref"

    write-host " Exchange team blog:            " -no
    write-host -fore Yellow "get-exblog"

    write-host " Show full output for a cmd:    " -no
    write-host -fore Yellow "<cmd> | format-list`n"
    }
    ## shows quickref guide
    function quickref{
        $culture = [System.Threading.Thread]::CurrentThread.CurrentUICulture.Parent

        if ( test-path "$($global:exbin)\$($culture.Name)\exquick.htm" )    {
    $culture = $culture.Name
        }
        else    {
    $culture = 'en'
        }

        if ( test-path "$($global:exbin)\$culture\exquick.htm" )    {
    invoke-item $global:exbin\$culture\exquick.htm
        }
        else    {
    "Exchange quickstart guide $global:exbin\$culture\exquick.htm not found!"
        }
    }
    function get-exblog{
           invoke-expression 'cmd /c start http://go.microsoft.com/fwlink/?LinkId=35786'
    }

    ## now actually call the functions
    get-exbanner
    get-tip
    write-host -foregroundcolor GREEN "Console Powershell personnalisé (Exchange 2007 + ActiveRole)"
  5. Nouveau raccourci vers notre console.
    %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -psconsolefile "C:\Powershell\Console\MaConsole.psc1" -noexit -command ". 'C:\Powershell\Console\StartConsole.ps1'"


Toutes les sources sont mise à disposition gratuitement mais vous les utilisez sous votre propre responsabilité.

0 commentaires:

Enregistrer un commentaire