Improving the output of Update-Help

December 20, 2012

Source: PowerShellMagazine.com

 

If you’ve updated PowerShell to version 3.0 you probably noticed that help is no longer shipped in the box. PowerShell 3.0 includes a new feature, the Updatable Help system, which allows you to ensure that help on the local computer stays up to date.

PowerShell is now a part of the operating system and operating systems gets to be updated only during service packs or specific patches. The Updatable Help system and its cmdlets (*-Help) make it easy to download and install help files, or updating exiting help files, as soon as newer help files become available.

To download and install help files for the first time, use the Update-Help cmdlet. When executed, Update-Help goes through a series of steps to get the latest help versions of the modules installed on your system:

  1. It determines which modules support updatable help by checking the HelpInfoUri key in the module manifest file.  The HelpInfoUri contains the Internet location where each module stores its updatable help files.
  2. Compares each module local help files with the newest help files that are available for each module.
  3. Downloads the new files (packaged in a cab file).
  4. Unwraps the help file package, verifies that the files are valid, and then installs the help files in the language-specific subdirectory of the module directory.

Note: There are a few things to take into account when using Update-Help. First, you must run PowerShell as an administrator as help files are written to the installation folder of PowerShell and that happens to be under theSystem32 folder. PowerShell allows you to update help files once every 24 hours. To override this behavior you must specify the -Force switch.

By default, the Update-Help cmdlet doesn’t generate any output. When executed, it displays a progress bar that prints information about the current module update phase.

updateHelp

If you want to see what’s going on under the hood, include the -Verbose switch:

updateHelp1

One of the things that really annoys me is the output of the -Verbose switch, the way it is written makes it very hard to read and determine which files and modules has been updated. In this post I want to introduce you to a new feature in PowerShell 3.0 that can help you change the way the verbose information is displayed in the console.

In the previous version of PowerShell it was very hard to capture the output of the Verbose stream, or any other PowerShell-related stream. Luckily, this has changed in PowerShell 3.0 and now it is a very easy thing to do. We can now redirect and merge any of the pipeline output streams (see list below) to text files. You can read more about this in about_Redirection help topic.

By default, the Update-Help command doesn’t write anything to the pipeline so we can safely merge the verbose stream to the standard output stream and parse it without having to worry about information from both sources gets mixed together.

Each redirection operator uses a character to represent each output type:

  • * – All output
  • 1 – Success output
  • 2 – Errors
  • 3 – Warning messages
  • 4 – Verbose output
  • 5 – Debug messages

The Verbose stream constant is 4, and Success output is 1, so we use the redirection operator (e.g ‘>’) to funnel the output:

PS> $uh = Update-Help -Verbose -Force 4>&1

Let’s examine the first element; we can see that the connection is redirecting to another URI.

PS> $uh[0]
VERBOSE: Your connection has been redirected to the following URI:
VERBOSE: http://download.microsoft.com/download/3/4/C/34C6B4B6-63FC-46BE-9073-FC75EAD5A136/

The second element in the output of Update-Help contains the information we are after. We can see that theMicrosoft.PowerShell.Management was updated, and we

also get information about the path of the help file, its culture, and the version information.

PS> $uh[1]
VERBOSE: Microsoft.PowerShell.Management: Updated
VERBOSE:
C:\Windows\System32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Management.dll-hel
p.xml. Culture en-US
VERBOSE: Version 3.1.0.0

Let’s see what Get-Member has to say about it:

PS> $uh[1] | Get-Member

   TypeName: System.Management.Automation.VerboseRecord

Name                  MemberType   Definition
----                  ----------   ----------
Equals                Method       bool Equals(System.Object obj)
GetHashCode           Method       int GetHashCode()
GetType               Method       type GetType()
ToString              Method       string ToString()
WriteVerboseStream    NoteProperty System.Boolean WriteVerboseStream=True
InvocationInfo        Property     System.Management.Automation.InvocationInfo InvocationInfo {get;}
Message               Property     string Message {get;set;}
PipelineIterationInfo Property     System.Collections.ObjectModel.ReadOnlyCollection[int] PipelineIterationInfo {get;}

We get a System.Management.Automation.VerboseRecord object which describes a verbose message sent to the verbose stream, and information about the command that sent the message (InvocationInfo). The Message property contains the actual message we see in the console. If you need to identify verbose messages written to the success stream, you can safely rely on this type and filter objects accordingly.

PS> $uh[1].Message
Microsoft.PowerShell.Management: Updated C:\Windows\System32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands
.Management.dll-help.xml. Culture en-US Version 3.1.0.0

We can split the message (by default the Split method breaks the string on the space character) and get access to the array elements we get back:

PS> $uh[1].Message.split()
Microsoft.PowerShell.Management:
Updated
C:\Windows\System32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Management.dll-help.xml.
Culture
en-US
Version
3.1.0.0

Based on the output of the Split operation, we want to extract the relevant pieces of information, create a new custom object and write it back to the pipeline, one object at a time.

The information we want is:

  1. The module name–it’s the first item (index 0). The value is followed by a colon, we’ll remove it later on.
  2. The file path that’s being updated (third line, index 2).
  3. The culture of the help file (fifth line, index 4).
  4. The version of the new help file (last line, we can refer to it as index -1, which in PowerShell gives back the last array element).

We can now construct a new custom object. We’ll start by creating a custom object for the first array element:

$message = $uh[1].Message.split()[0,2,4,-1]

[PSCustomObject]@{
	Module = $message[0] -replace ':$'
	FileName = (Split-Path $message[1] -Leaf).Trim('.')
	Culture = $message[2]
	Version  = $message[-1]
}

Module                        FileName                      Culture                       Version
------                        --------                      -------                       -------
Microsoft.PowerShell.Manag... Microsoft.PowerShell.Comma... en-US                         3.1.0.0

As soon as each object (verbose message) is processed, the object goes out to the console. As you can see, the output of the Module and FileName properties is truncated.

We could use the -AutoSize of the Format-Table cmdlet to adjust the columns size, but doing so will block output of objects to the console until all objects were processed.

When processing the verbose stream we also want to avoid processing unnecessary messages, we want to skip any messages that contains URI redirections, so we process only messages that contains the word “Updated”. We pipe the custom objects to the Tee-Object cmdlet, to send output to the console as soon as it flows in, and also save the output to a variable that we can format the way we want it to.

Here’s the full snippet. Output shown on screen is also saved in the UpdatedHelp variable. When the script finished executing we can investigate and format it as we like.

Update-Help -Force -Verbose 4>&1 |
Where-Object {$_.Message -like '*: Updated*'} |
ForEach-Object {

    $message = $_.Message.Split()[0,2,4,-1]

    [PSCustomObject]@{
        Module = $message[0] -replace ':$'
        FileName = (Split-Path $message[1] -Leaf).Trim('.')
        Culture = $message[2]
        Version  = $message[-1]
    }

} | Tee-Object -Variable UpdatedHelp

$UpdatedHelp | Format-Table -AutoSize

 

updateHelp2

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

18 comments

  1. グッチコピーDecember 23, 2012 ב 08:07

    この人が脱退してから、AKBの話題が減った気がする。

    Reply
  2. ブランド時計December 23, 2012 ב 14:49

    品質がよい、価格が低い、実物写真!当社の商品は絶対の自信が御座います。100%品質保証 !満足保障100%!

    Reply
  3. GraliaExhauraMay 4, 2013 ב 06:09

    You created some decent points there. I looked on the web for the concern and discovered most individuals will go along with along with your web page.

    [URL=http://www.mkbagforcheap.com]michael kors bags[/URL]

    Reply
  4. http://www.foakleysq4.comAugust 13, 2013 ב 08:11

    She was born in a log cabin in a rural county in Western Ohio, which at that time was still frontier.

    Reply
  5. Toms OutletAugust 16, 2013 ב 00:02

    Scientists at the (EFSA), together with experts from across Europe, concluded on Wednesday that for imidacloprid “only uses on crops not attractive to honeybees were considered acceptable” because of exposure through nectar and pollen. Crops that attract honeybees include oil seed rape, corn and sunflowers. EFSA was asked to consider the acute and chronic effects on bee larvae, bee behaviour and the colony as a whole, and the risks posed by sub-lethal doses. But it found a widespread lack of information in many areas and had stated previously that .
    Toms Outlet http://magickshaman.com
    Toms Outlet

    Reply
  6. レイバン メガネAugust 16, 2013 ב 11:57

    Aravind Jagadeesh, consultant, general medicines and diabetology, Bhagwan Mahaveer Jain Hospital agrees that gastro-intestinal (GI) disorders are the main problems to watch out for this summer. This can be manifested in the form of vomiting and dysentery sometimes accompanied by slightly elevated body temperature. “If these symptoms persist the person should be taken to a doctor immediately, because in this kind of weather dehydration can occur very quickly,” says Dr Jagadeesh.
    レイバン メガネ http://www.pettittrays.tk

    Reply
  7. プーマ スニーカーAugust 16, 2013 ב 12:11

    In statement on Tuesday, Wyden said: “One of the most important responsibilities a senator has is oversight of the intelligence community. This job cannot be done responsibly if senators aren’t getting straight answers to direct questions.”
    プーマ スニーカー http://www.showstorejapan.com

    Reply
  8. http://www.janpanfashiononline.com/WORLD%20MARCH%20/ワールドマーチ-4412/August 16, 2013 ב 16:46

    Samir Nashar, a member of the opposition Syrian National Council’s executive board, blamed the state for the bombings, saying they were meant to deter protesters and U.N. monitoring, an argument echoed by rebel Free Syrian Army (FSA) leaders.

    Reply
  9. Louis Vuitton Mens LuggageAugust 16, 2013 ב 16:46

    Joyce Ann Huston of Las Vegas has been a musician her entire life and is one of the 26 percent of Americans who say that they or a family member have struggled to pay medical bills in the last year, according to the Kaiser Family Foundation.

    Reply
  10. ナイキ ランニングAugust 16, 2013 ב 17:42

    Cartwright praised Mullens handling of questions from Republicans, saying he is a “consummate professional” with an “extraordinary command of the facts.”
    ナイキ ランニング http://www.japanshoesoutdoor.com

    Reply
  11. ROYAL ELASTICS /ロイヤルエラスティックス 販路August 17, 2013 ב 21:03

    “Russia has stabbed us in the back, and each day that Mr.Snowden is allowed to roam free is another twist of the knife,”said Senator Chuck Schumer, a close Obama ally and fellowDemocrat who urged Obama to recommend moving out of Russia thesummit of G20 leaders planned for St. Petersburg.

    Reply
  12. スニーカーAugust 20, 2013 ב 07:06

    “As time progressed, we wanted to provide our customers with even better Maps including features such as turn-by-turn directions, voice integration, Flyover and vector-based maps,” he said in the letter. Google provides turn-by-turn navigation on Android-based devices but the popular feature was not available for Apple devices. Apple Maps replaced Google Maps in iOS 6 and the Google service is now only available through a browser. Shares of Apple fell 2% to close at $667.10 on Nasdaq.Apple Inc has cut orders for LCD screens and other parts for the iPhone 5 this quarter due to weak demand, the Nikkei reported on Monday, in a further sign the US firm is losing ground to Asian smartphone rivals.
    スニーカー http://www.japaneseshoesstore.com/

    Reply
  13. MONDAINE モンディーン販路August 21, 2013 ב 17:19

    MIKE KASTNER, HEAD OF FIXED INCOME AT HALYARD ASSET MANAGEMENT IN WHITE PLAINS, NEW YORK:

    Reply
  14. 公式 激安 人気 安いAugust 26, 2013 ב 03:22

    Live updates via Twitter:What You Should Know About Comments on Sacbee.com
    公式 激安 人気 安い http://www.japandesignfactory.com/

    Reply
  15. 良い 工場出荷時の価格 高品質 最低価格 DANNER ダナーAugust 27, 2013 ב 14:53

    In contrast, Labour has deployed a brave, but politically unsustainable, defence of the first. And been guilty of total incoherence on the second.
    良い 工場出荷時の価格 高品質 最低価格 DANNER ダナー http://www.japankakufactory.com/DANNER%20%20%E3%83%80%E3%83%8A%E3%83%BC-20878/

    Reply
  16. Pronto /プロント 安売り 店舗 ポピュラーAugust 27, 2013 ב 19:10

    The UPM microprocessor 361 and ASIC 363 communicate with the system motherboard microprocessor 329 on the M-bus 373. The motherboard tuner 317 can receive all cablecast channels whereas the simulcast tuner receives only channels having digital information. The control data downloaded by the CDC instructs the motherboard microprocessor 361 which channels are video with analog audio, video with digital audio replacing the analog audio, video with a simulcast broadcast and digital radio. When a DCR module 303 having a simulcast tuner 375 is installed, a jumper normally coupling the IF output of the system motherboard tuner 317 to a 41.25 MHz passband surface acoustic wave (SAW) filter 391 is removed allowing the output of the simulcast tuner 375 to pass to the SAW filter 391. If a DCR module not having a simulcast tuner 375 is installed, the jumper 389 remains in place.

    Reply
  17. umnodomaaAugust 29, 2013 ב 15:09

    Как получить систему видеонаблюдения бесплатно сегодня, чтобы уже завтра наблюдать за своими сотрудниками не выходя из дома?

    Представьте, как Вы сидите дома, берете свой телефон, запускаете одно приложение и, вуаля… Весь офис перед Вашими глазами! Смотрите, как работают сотрудники, что они делают и с кем общаются. Пресекайте любые попытки воровства и нанесение ущерба компании.

    А теперь подумайте о том, что такая система видеонаблюдения может быть установлена у Вас уже завтра БЕСПЛАТНО!

    Мы предлагаем Вам абсолютно бесплатно попробовать систему удаленного видеонаблюдения в течение 7 дней. Оцените эффективность данного инструмента, который позволит увеличить Вашу прибыль, сократить издержки и увеличить эффективность персонала.

    Что для этого нужно сделать?

    Возьмите телефон и позвоните нам по номеру (812) 715-44-11 или 8-800-333-33-24 (бесплатно для всех мобильных) и мы согласуем время и место установки видеонаблюдения.

    P.S. каждому заказавшему бесплатный тест видеонаблюдения мы бесплатно подарим 1 микрофон при оплате системы, чтобы Вы могли слушать переговоры сотрудников и то, как они общаются с клиентами!

    P.P.S. В месяц мы можем бесплатно устанавливать только 10 систем видеонаблюдения. На текущий момент осталось всего 3 свободные системы. Торопитесь, возможно Вы еще успеете увеличить эффективность своего бизнеса бесплатно!

    Reply