Exchange 2007 console tips and tricks

Exchange Server 2007 introduced a new GUI management console (Exchange Management Console) to replace the Exchange System Manager (ESM) of previous versions. This earlier blog post The new Exchange 2007 Management Console overview gives an overview of the console. In this blog post I’ll show some tips and tricks of the console.

Tip#1: Specify the domain controller for your configuration data

Under the Organization Configuration or Server Configuration node, there is a “Modify Configuration Domain Controller” context menu to launch the Configuration Domain Controller dialog. This allows you to specify a domain controller to be used for AD read and write for organization or server configuration.

This is possible in Exchange 2003 ESM by selecting the DC to be used when manually adding Exchange System Manager snap-in into an MMC session, but it’s a lot easier here in Exchange 2007!

Tip#2: Modify the scope and the maximum number of recipients to display

By default, recipients in the current domain and up to 1000 maximum recipients are displayed in the result pane of the Recipient Configuration node. It may take quite a long time to load all recipients if there are a lot of recipients to display. Administrators can control the scope of recipients shown to be the whole forest, a whole domain, or by OU within a domain by using the “Modify Recipient Scope” context menu of the Recipient Configuration node. There is also a “Modify the Maximum Number of Recipients to Display” context menu to control the maximum number of recipients to display in the GUI.

Setting your scope controls which recipient objects will be displayed in the GUI result panes, and also controls which recipient objects will be found by the GUI pickers in many cases. For instance, if you configure your scope to be a particular OU, then you will only be able to specify this OU or one of its children as the target of a new mailbox creation and you will only be able to select a user from this OU or one of its children while enabling a mailbox. This can help to reduce the size of the result-set you have to filter through while doing administrative tasks if your tasks are easily scoped to a particular part of the directory!

In the Active Directory Users and Computers (ADUC) tool you see objects only under an OU scope, while Exchange 2007 recipient management allows you to define your scope to be an OU, domain, or even forest-wide increasing administrative flexibility!

Tip#3: Equivalent Shell One-liner provided after completion of each wizard

Since the Exchange Management Console builds on top of Exchange Management Shell (EMS), every wizard runs one or more “one-liners” (single-line of EMS command) to achieve the work required of the wizard. The one-liner for each wizard is displayed at the Completion page. This can be copied (Ctrl+C) and the command portion can then be pasted to be run in EMS cmdline.

The one-liner can be used as an example of the required syntax and altered to meet specific needs while learning PowerShell scripting.

Tip#4: Filtering

Filters are used in the result pane for Server Configuration and Recipient Configuration nodes and within picker dialogs.

Administrators can save a filter as the default filter, so that next time this filter is used when the result pane is visited. Just like specifying OU as the recipient scope, filtering by certain attributes also improve UI performance if there are a large number of recipients to display.

One great example of how this can be used is to simulate an Administrative Group view using filtering. Simply create a filter in the Server Workcenter that specifies the criteria used to distinguish your servers into your desired “Administrative Group” set – based on some aspect of server name or based on AD site membership, for instance!

Look for a separate blog post on Filtering soon!

Tip#5: Set visual effects of the Console

Visual Effects is another option which can be configured for the console. It can be used to set the visual effects to be always on, never on, or automatic.

Visual effects setting controls how Exchange wizards display by enabling or disabling the cool Exchange 2007 “skin” applied to the wizards by default. .

You might want to turn this off if you prefer the classic look within the console or if you experience performance issues with the visual effects.

Tip#6: Show/Hide the action pane in the console window

Action pane is shown to the right side of Exchange Management Console by default. It lists actions that are currently available to the selected node in the navigation tree and selected objects in the result pane. These options are also available as context menu items for the selected node or objects.

Action pane can be hidden to provide more space in the control window, by un-checking the Action pane checkbox in the Customize View dialog. The Customize View dialog can be launched via the View->Customize menu.

Tip#7: Modify the number of items to display on each page of Queue Viewer

To change the number of queues or messages on the Queues page or Messages page, specify the “Number of items to display on each page” field in the Queue View Options dialog. The value 1000 is used by default.

You can use this setting to control the number of items included in each page shown in the Exchange 2007 queue viewer. No matter what value you use here, the number of items shown will be complete – for instance, if you have 10 pages shown with 1000 items per page, you can modify this value to end up with 1 page of 10000 items each or to 100 pages of 100 items each.

Tip#8: Create a custom console snap-in

It’s possible to create a custom console snap-in for any of the 4 nodes under the root Microsoft Exchange node in the EMC navigation tree. This “reduced” custom console can be used to isolate visibility of additional management capabilities of the Exchange 2007 management console. Below are the steps creating a Recipient Management only console, which exposes just recipient management capabilities to administrators or helpdesk:

Step 1: Open MMC.exe directly (no snap-ins added)

Step 2: Add the Exchange Snap-in to this empty MMC console

Step 3: Select the Recipient Configuration node. Right click and choose “New Window from Here”

Step 4: Under File->Options, configure the Console mode as desired.

Step 5: Save this custom MMC to an MSC file. This MSC file can be used to launch your new Recipient Management only console!

Below is a snapshot of a Recipient Management only console:

The steps creating a reduced console for Organization Configuration, Server Configuration and Toolbox are the same except in Step3, the appropriate node should be selected.

Tip#9: Use the error provider information

In most cases, when you have something entered incorrectly within Exchange 2007 console property pages or wizards, the console will let you know something isn’t entered correctly by producing an error provider icon (!) next to the incorrect entry. Hover over this error provider to get more information on the cause of the failure.


(from : http://blogs.technet.com/b/exchange/archive/2006/10/20/3395119.aspx)

Exchange Server 2007 Deployment: 10 Tips When Installing

(From : http://technet.microsoft.com/en-us/library/aa996011(v=exchg.65).aspx)

Topic Last Modified: 2006-10-20

With Microsoft Exchange Server 2007, deployment is easier than it’s ever been. Take a look at some of the major improvements to Exchange 2007 Setup:

  • The Setup wizard has a new look! It is easy to use and effortlessly guides you through the installation.
  • Setup is role-based, which means you can deploy individual server roles. Having the capability to select which server roles you want to deploy provides you with the flexibility to design an Exchange topology that is customized for your needs.
  • By using the engine from the Microsoft Exchange Best Practices Analyzer Tool, all of the deployment prerequisites are automatically checked. Just like the Exchange Best Practices Analyzer Tool, the Setup wizard provides detailed information about any prerequisites that are not met so that you can make any necessary changes to you computer or your environment. Then you can either retry the prerequisite check or run the Setup wizard again.
  • Before checking the prerequisites, Setup attempts to retrieve the latest version of the prereq.xml file from www.microsoft.com. This way, you will always have the most up-to-date prerequisite checks before you begin.

Even with all the great improvements to Exchange 2007 Setup, there are still a few things you should know before you install Exchange 2007. This article presents the top 10 issues that our very first Exchange 2007 customers have discussed, stumbled upon, and requested guidance about.

  1. When deciding which server roles to install in your organization, be aware that, to send e-mail, you must install the Hub Transport server role. The Hub Transport server handles all mail flow in your Exchange organization. Even e-mail that is sent from one mailbox to another mailbox on the same Mailbox server must be processed by the Hub Transport server. You can install the Hub Transport server role and the Mailbox server role on the same computer or on separate computers, but these two server roles are essential for mail flow and mail storage.
    • For more information about the technical architecture of the Hub Transport server role, see Hub Transport.
    • For more information about the technical architecture of the Mailbox server role, see Mailbox.
    • For more information about transport architecture, see Transport Architecture.
  2. If you are installing Exchange on a cluster, you can breathe a sigh of relief because a few improvements have made this installation much easier in Exchange 2007. First, setting up clustered Mailbox servers is integrated into Exchange 2007 Setup. Second, less customization is needed after installation because many of the default values that are associated with clustered Mailbox servers have been set to meet the needs of most organizations. And third, you can use both the Exchange Management Console and Exchange Management Shell to manage Exchange clusters. So, with Exchange 2007, you can say goodbye to Cluster Administrator for performing Exchange cluster administration tasks.
    The following steps provide a brief overview for installing Exchange 2007 on a cluster, links to more information, and answers to a few questions you might encounter during installation.
    Step 1: Determine if you will use single copy clusters (SCCs) or cluster continuous replication (CCR). SCCs are very similar to clusters in Exchange 2003 or Exchange 2000: shared storage of mailbox data with multiple servers that are allowed to own the shared storage. CCR combines the failover features of a cluster with asynchronous log shipping and replay features. For more information, see the following topics:

    Step 2: Plan for your cluster deployment. For more information, see either Planning for Cluster Continuous Replication or Planning for Single Copy Clusters.
    Step 3: Install the cluster. This involves configuring the cluster network, configuring the cluster servers, and finally, installing Exchange 2007 on the servers. Be aware that you do not have to create a cluster group with a network name resource and an IP address resource before you run Setup. In Exchange 2007 Setup, if you select Active Clustered Mailbox Role, these resources are created as part of Setup. When you install Exchange 2007 on the servers, it does not matter if you first install the active node or the passive node. Just select either option in the Setup wizard. For more information, see the following topics:

  3. If your organization contains many Exchange servers, it is possible that more than one person will be installing Exchange 2007. As a result, you might not want every person who will install Exchange 2007 to have the permissions assigned to the Exchange Organization Administrators role (even though that is the requirement for installing Exchange 2007). Good news! There is a way around this: You can delegate setup. To delegate setup, you must first run Setup.com from a Command Prompt window with the /NewProvisionedServer parameter. This will not install Exchange 2007 on the server, but instead will create a placeholder object for the server in Active Directory and will add the machine account for this server to the Exchange Servers group. Then you can add a user to the Exchange Server Administrator role for the server that you provisioned. Adding a user to the Exchange Server Administrator role will add the user’s account to the View-Only Administrator group and will set permissions on the placeholder server object in Active Directory so that the user account can install and administer Exchange 2007 on that server. For more information about how to add a user to the Exchange Server Administrator role, see How to Add a User or Group to an Administrator Role.
    Aa996011.note(en-us,EXCHG.65).gifNote:
    To install the first instance of each server role in an organization, you must use an account that has the permissions assigned to the Exchange Organization Administrator role. You cannot delegate setup of the first instance of a server role.
  4. Even with all the robust and user-friendly prerequisite checking in Exchange 2007 Setup, it is possible that Setup could hit a snag and fail. To troubleshoot Setup, use the log files located at %systemdrive%ExchangeSetupLogs. You will see several log files in this directory. The most relevant is the ExchangeSetup.log file. To find out where Setup ran into problems, search this file for “[ERROR]”.
    Other files in the ExchangeSetupLogs directory include the following:

    • *.msilog files. These files include additional logged information about specific parts of the installation.
    • *.ps1 files. These files are Exchange Management Shell scripts that Setup calls during the installation. To view where in the installation process each of these scripts was run, search for the file name in the ExchangeSetup.log file.
    • Prerequisites check logs. These logs are located in the PreReqs directory, which contains logs and data files from the Setup prerequisite checks. These filenames all start with “ExBPA” because the prerequisites are checked by using the engine from the Exchange Best Practices Analyzer Tool.

    Here’s another great feature: After you troubleshoot a Setup failure and make any necessary changes, you do not have to reformat the drive or remove the Exchange files that were copied and then start over from scratch. Setup can pick up right where it left off! Simply run Setup.com from a Command Prompt window, or click Setup.exe to start the Setup wizard, and it will continue with the previously attempted installation. Or, if you leave the Setup wizard open on the Readiness Checks page, you can make any necessary changes and then click Retry to run the readiness checks again and continue with the installation.

    Aa996011.note(en-us,EXCHG.65).gifNote:
    If Setup successfully installs at least one server role and then fails, when you restart the Setup wizard, you will be in maintenance mode. This means that you already have at least one component of Exchange 2007 installed. You can also start Setup in maintenance mode by runningAdd or Remove Programs from Control Panel and selecting either Change or Remove for Microsoft Exchange Server. In maintenance mode, you can add server roles. If you select Remove from Control Panel, you can also remove server roles. For more information, seeRemoving and Modifying Exchange 2007.
  5. Even after you successfully complete the Setup wizard, you are not finished deploying Exchange 2007. Open the Exchange Management Console, select Microsoft Exchange in the console tree, and then select the Finalize Deployment tab. This tab lists various tasks and configuration options for each server role that you installed. The tasks on this tab apply to features that are enabled by default in Exchange 2007, but require additional configuration.
    It is also a good idea to select the End-to-End Scenarios tab and configure the end-to-end solutions for Exchange 2007. The configuration tasks on this tab are optional. Depending on which Exchange 2007 features you want to use, you can choose which tasks to complete.
    For more information about these tabs, see the following topics:

  6. In a coexistence scenario with Exchange 2007 and either Exchange 2003 or Exchange 2000, make sure your routing group connectors are configured correctly. By default, when you install the first Exchange 2007 Hub Transport server in an existing Exchange 2003 or Exchange 2000 organization, Setup creates a new routing group for all Exchange 2007 servers and requires you to specify an Exchange 2003 or Exchange 2000 bridgehead server to which it will connect the new Exchange 2007 routing group. By default, the Exchange 2007 routing group that is created is called the Exchange Routing Group (DWBGZMFD01QNBJR), and must not be renamed. Setup creates two reciprocal routing group connectors between the specified bridgehead server and the Hub Transport server that you are installing.
    By default, you now have one Exchange 2007 routing group and two reciprocal routing group connectors between the first Hub Transport server that you installed and one bridgehead Exchange 2003 or Exchange 2000 server. You may want to consider creating additional routing group connectors. For redundancy, it is a good idea to connect additional Hub Transport servers in your Exchange 2007 routing group to the bridgehead servers in your Exchange 2003 or Exchange 2000 routing group. If your existing Exchange 2003 or Exchange 2000 organization had more than one routing group, you may want to consider installing the first Hub Transport server in the “hub” Exchange 2003 or Exchange 2000 site. As you add more Hub Transport servers to different sites, you may want to create routing group connectors between these Hub Transport servers and the existing routing groups in other sites as well. This provides for a logical mail route between Exchange 2007 servers and legacy servers in different sites.
    When Setup creates the initial routing group connector between the first Hub Transport server and the specified legacy bridgehead server, that legacy bridgehead server is automatically added to a universal security group (USG) called ExchangeLegacyInterop. Members of this USG have the permissions required to send e-mail to and receive e-mail from Exchange 2007. If you create additional routing group connectors between the Exchange 2007 routing group and routing groups from your existing Exchange 2003 or Exchange 2000 organization, you must use the New-RoutingGroupConnector cmdlet in the Exchange Management Shell. If you use this cmdlet, the Exchange 2003 or Exchange 2000 bridgehead server to which you connect will also be added to the ExchangeLegacyInterop.
    For more information, see the following topics:

  7. In a coexistence scenario with Exchange 2007 and either Exchange 2003 or Exchange 2000, be sure to use the correct management interface for managing mailboxes and servers.
    To manage Exchange 2003 or Exchange 2000 users and mailboxes, you should continue to use Exchange System Manager and Active Directory Users and Computers on the Exchange 2003 or Exchange 2000 servers. Additionally, you can modify and remove Exchange 2003 or Exchange 2000 mailboxes with Exchange 2007 tools, but you cannot create mailboxes on Exchange 2003 or Exchange 2000 servers with Exchange 2007 tools.
    To manage Exchange 2007 users and mailboxes, you must use the Exchange Management Console or the Exchange Management Shell in Exchange 2007. You will not be prevented from using the Exchange 2003 or Exchange 2000 System Manager and Active Directory Users and Computers to manage Exchange 2007 mailboxes, but Exchange 2007 mailboxes that are managed with these Exchange 2003 and Exchange 2000 tools will not be fully functional.
    Although Exchange 2007 objects (such as servers, storage groups, databases, protocols) and global objects (such as address lists and e-mail address policies) are visible in Exchange 2003 or Exchange 2000 System Manager, you should not use Exchange System Manager to manage those Exchange 2007 objects.
    In general, your best bet is to not mix and match management tools across different versions of Exchange.
    For more information, see Transferring Settings from Exchange Server 2003 to Exchange 2007.
  8. Make sure that the Autodiscover service is configured for your topology. Installed by default with the Client Access server role, the Autodiscover service allows Microsoft Office Outlook 2007 and supported mobile devices to automatically connect to Exchange without having to manually configure profiles. The Autodiscover service does not require additional configuration only if the following conditions are true:
    • You have a single Exchange forest
    • You are not providing external access to Exchange using Outlook Anywhere

    If you have multiple Exchange forests, or if you have an Exchange resource forest, you must create an Autodiscover service connection point (SCP) object in Active Directory in each forest.
    If you want to provide external access to Exchange by using Outlook Anywhere, you must configure a valid Secure Sockets Layer (SSL) certificate on the Client Access server.
    If you have a large distributed organization that has sites that are separated by low-bandwidth network connectivity, you may want to configure the Client Access server to which the Outlook 2007 clients in a particular site will connect.
    To learn more about the Autodiscover service, see Overview of the Autodiscover Service.
    For more information about each of these configuration changes, see Deployment Considerations for the Autodiscover Service.

  9. Make sure that the Availability service is configured for your topology. Installed by default with the Client Access server role, the Availability service improves information workers’ free/busy data by providing secure, consistent, and up-to-date free/busy information to computers that are running Outlook 2007. The free/busy data is provided to client computers only if the following conditions are true:
    • You have a single Exchange forest
    • You have only Exchange 2007 servers, no Exchange 2003 or Exchange 2000 servers in the organization
    • The client computers are running Outlook 2007

    If any of these conditions is not true, the default configuration of the Availability service may not be enough for clients to view free/busy data. You must verify additional configuration to be sure that the Availability service will work for the mailboxes in your topology.
    If you have multiple Exchange forests, you must first install and configure the GAL Synchronization (GALSync) feature in Microsoft Identity Integration Server (MIIS) 2003. Next, if you have client computers that are running Office Outlook 2003 or earlier, you must install and configure the Microsoft Exchange Inter-Organization Replication tool. Finally, if you have trusted forests in your topology and want to configure the Availability service for per-user free/busy data, you must use the Exchange Management shell to configure the Availability service. For more information about configuring the Availability service if you have multiple Exchange forests, see How to Configure the Availability Service for Cross-Forest Topologies.
    If you have Exchange 2003 or Exchange 2000 servers in your organization, or if client computers in your organization are running earlier versions of Outlook, free/busy information for mailboxes on those servers will be published in public folders. Make sure you have public folder stores on your Exchange servers so that mailboxes on different versions of Exchange can publish and retrieve free/busy information. For more information about the different methods used to retrieve free/busy information, see How to Configure the Availability Service for Network Load Balanced Computers.

  10. Now that you’ve deployed Exchange 2007, it’s time to learn all you need to know about the Exchange Management Shell. Where do you start? How do you find the correct command and the correct syntax to use for a specific task? Here are a few tips to get you started:
    • Learn from the Exchange Management Shell information provided in the graphical user interface (GUI). Each time you use an Exchange Management Console wizard to perform a task, the wizard’s Completion page lists the Exchange Management Shell command that was used to perform the task. Familiarize yourself with these commands as you perform common administrative tasks.
    • Get help directly in the Exchange Management Shell. Each command has Help information available. The Exchange Management Shell Help includes a description, the syntax to use, all available parameters, permission needed to run the command, examples of how to use the command, and more. You can view all of the Help information for a particular command, or only a specific piece. For more information, seeGetting Help.
    • Use the full Exchange Server 2007 Help documentation. To open the Help file on an Exchange 2007 server, click Start, point to All Programs, point to Microsoft Exchange Server 2007, and then click Exchange Server Help. To view the Help file online, see the Exchange Server 2007 Online Documentation.
      The Help topics for each Exchange Management Shell cmdlet are located under Technical ReferenceExchange Management Shell in the Help file.
    • Use the TAB key to complete cmdlets and parameters in the Exchange Management Shell. For example, if you type “Get-Exchange” and then press TAB, the Exchange Management Shell will complete the command Get-ExchangeAdministrator. Press TAB again, and the Exchange Management Shell changes to the next command that starts with Get-Exchange: Get-ExchangeCertificate. Press TAB a third time and you get Get-ExchangeServer. If you don’t remember what parameters are available for a command, the TAB key will help fill those in as well. Type “get-ExchangeServer -” and then press TAB to scroll through all the available parameters for this cmdlet. Or type as much of a parameter as you remember and press TAB to fill in the rest.

(Issu de : http://technet.microsoft.com/fr-fr/library/aa996011(v=exchg.65).aspx)

Validate an email address

Exchange PowershellValidating an e-mail address could be really usefull. Here is a really good thing to do before sending that address to a creation/modification script :

Function ValidMail ([string]$Mail ) {
$regexp=”^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}” +
“.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+” +
“.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$”

if ($Mail -match $regexp) {
$return=$True
}
Else {
$return=$False
}
Return $return
}

$regexp contains a regular expression that can validate any mail address, with many sub-domains, and can also contains an IP address in case of…

 

Exploring WMI

WMI is an acronym for Windows Management Instrumentation. WMI is the Microsoft’s implementation of Web-Based Enterprise Management (WBEM) – a new management technology that allows software to monitor and control managed resources throughout the network. Such managed resources include hard drives, file systems, settings of operating system, processes, services, shares, registry settings, networking components, event logs, users, groups, etc.
WMI allows monitoring of performance counters as well. Microsoft applications such as Exchange and SQL Server have WMI built-in. Many non-Microsoft applications utilize WMI and thus they could be monitored using Advanced Host Monitor as well.

You can download WMI Explorer at : http://www.hostmonitor.biz/download/wmiexplorer.zip 

Let’s see this page for more information !

 

 

Active Directory – Get a Free Domain Controller

It could be really usefull to use the -DomainController parameter with many Powershell commands… But How to be sure to find an available DC ?

A little function will help you to do that :

Function Get_Domain_Controller {
$site = [System.DirectoryServices.ActiveDirectory.ActiveDirectorysite]::GetComputerSite()

$back = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().FindDomainController($site).Name
return $back
}

Thanks to .Net to exist !

Sending mail using Powershell

Sending an email in powershell can be done, once more, using .Net Frameword 🙂

Function SendMail([string]$file,[string]$sender,[string]$recipients,[string]$server){

$message = new-object System.Net.Mail.MailMessage

$message.from = $sender

$message.subject = “My first mail in Powershell”

$message.body = “Hello,” + “`r`n” +”This mail was sent automatically by the script” + “`r`n” +”You will find in attachement all information  you asked.” + “`r`n” +”Regards”
foreach ($rec in $recipients){$message.TO.add($rec)}

$attachment = new-object System.Net.Mail.Attachment $file
$message.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $server
$client.Send($message)
$attachment.Dispose()
}

Four parameters aremandatory to get all the power of that function : $fichier, $sender, $recipients, $server.

$file : Contains the exact path of the file to include as attachment. (“C:includesfile.doc”)

$sender : Simply the email address of the sender (“sender@mydomain.com”)

$recipients : Contains a list of recipient with that format :

recipient1@domain.com

recipient2@domain2.com

$server : It is the full name of the server that is allowed to send mails.

SQL Requests & Powershell

It could be really hard to find something interesting on the web when we encountered a trouble in Powershell.

After a long search, I found it ! So, let’s share..

A request in SQL using powershell can be send using .Net Frameword.

You should have in mind that SQL request through powershell are exactly the same like standard SQL requests !

Here is an example with a simple Select :

$conec = “server=;database=;Integrated Security=sspi”
$cmd = “SELECT FROM WHERE ”
$da = new-object System.Data.SqlClient.SqlDataAdapter ($cmd, $conec)
$dt = new-object System.Data.DataTable
$da.fill($dt)

The “Integrated Security” allow to use Windows Authentication, so the account used to launch the powershell script should have rights on the Database !

The SQL request’s results are contained into the “$dt” variable.

So… Let’s “play” now !

(french) Tutoriel Powershell – 3

 

Passez à la vitesse supérieure avec les objets

Maintenant que vous savez tout sur les objets, ce paragraphe va vous permettre d’optimiser l’utilisation de vos objets, car même s’il est intéressant de disposer d’un petit script, sans aucun doute très pratique, il est encore plus intéressant de transformer ce script en une ligne de commande et pourquoi pas d’en faire un alias.

Voici quelques exemples :

Exemple Nº1 

PS C:> Get-Command | Foreach {Get-Help $_ -detailed |Out-File -FilePath C:temp$_.txt –Encoding ASCII}

En détail:

1ère instruction : Get-Command on récupère la liste des commandes PowerShell

2èmeinstruction : Foreach {Get-Help $_ -detailed pour chaque élément on affiche l’aide détaillée

3èmeinstruction : Out-File -FilePath C:temp$_.txt –Encoding ASCII} on envoie le résultat de la commande précédente dans un fichier texte portant le nom de l’élément.

Résultat : Pour chaque commande PowerShell, on extrait l’aide associée (au format détaillé) et on l’envoie dans un fichier texte portant le nom de la commande.

Exemple N°2  

PS C:> Get-ChildItem C:temp | ForEach-Object {$_.Get_extension().toLower()} | Sort-Object | Get-Unique| Out-File –FilePath C:tempextensions.txt -Encoding ASCII

Voilà de quoi vous mettre en jambe, cinq instructions sur une ligne le tout passant par des pipelines.

En détail :

1ère instruction : Get-ChildItem C:temp on va lister tout les éléments du répertoire C:temp

2èmeinstruction : ForEach-Object {$_.Get_extension().toLower()} pour chaque élément on va afficher son extension

3èmeinstruction : Sort-Object on va trier les éléments

4èmeinstruction : Get-Unique on supprime les occurrences en doublon

5èmeinstruction : Out-File –FilePath C:tempextensions.txt -Encoding ASCII on envoie le tout dans un fichier texte en mode ASCII.

Résultat : cette ligne de commande affiche dans un fichier texte les différentes extensions que l’on peut trouver dans le répertoire C:temp.

 

(french) Tutoriel Powershell – 2

 

Constitution des commandes PowerShell

Les commandes de PowerShell sont appelées « cmdlets »  (pour command-applets). Elles sont pour la plupart d’entre elles constituées de la manière suivante : un verbe et un nom séparés par un tiret (-), exemple : « Get-Command » (commande qui liste les commandes disponibles).

Le verbe (en anglais bien sur) décrit l’action que l’on va appliquer sur le nom. Dans cet exemple on va récupérer (Get) les commandes (Command).

Avec PowerShell on trouve toute une série de verbes d’action (GetSetAddRemove, etc.) qui sont applicables avec différents noms comme PathVariableItemObject etc.

On peut donc en croisant les verbes et les noms se souvenir de bon nombre de commandes

Découverte des commandes de base

Une des commandes les plus basique pour débuter, est de lister toutes les commandes disponibles. La commande appropriée à cette tâche est : « Get-Command ».

Pour utiliser cette aide il suffit d’appeler la commande la plus importante de PowerShell : Get-Help (ou son alias help) suivie de la commande en question.

Exemple pour avoir de l’aide sur la commande Get-Command on utilisera : « Get-Help Get-Command ».

Les Alias

Un alias est ce qu’on pourrait appeler un surnom d’une commande, ils sont souvent utiles lorsque l’on utilise des commandes un peu longues à taper, exemple : l’alias «ma_commande» pourrait être attribué à la commande « elle_est_vraiment_trop_longue_à_taper_cette_commande ».

Pour les utilisateurs de Dos et même de Linux (!) les commandes du type “mkdir”, “cls” etc.. ou encore “ls”, “grep”, etc.. sont également incluses dans Powershell !

En fait, ces commandes sont des alias de commande PowerShell.

Exemple : ls est un alias de la commande Get-ChildItem qui liste les fichiers et les répertoires.

Pour rechercher tous les alias de votre session, tapez : « Get-Alias »

Pour créer un alias tapez : « Set-Alias -Name #nom de l’alias# -Value #la commande# ».