ProfileKeith Hill's BlogPhotosBlogListsMore ![]() | Help |
Keith Hill's BlogWindows PowerShell MVP / P.S. I'M A PC AND I'm Running Windows 7
July 06 Get-TfsPermssion–Missing command from Team Foundation Power Tools PowerShell SnapinThe TFPT PowerShell snapin is a nice start but it is missing a key cmdlet IMO and that is Get-TfsPermission. Since TFS allows you to add individual users all over your directory structure, it can be quite hard rationalizing exactly who has access to what without traversing a bunch of directories in the Team Foundation client’s Source Control window, opening the Properties dialog and inspecting the Security settings. Fortunately there is also a command line way to do this via TFS’s tf.exe utility. Unfortunately the output of this command is just text and what’s worse is that this text is a pain to query over using PowerShell’s built-in querying cmdlets. So I wrote the following function to convert this text into objects which enables easier querying: <# Begin Process End The output of this function isn’t great for viewing since it is primarily intended to enable querying of the permission info on each server item. Note to the Team Foundation Power Tools devs, it sure would be nice to get this functionality into a future TFPT drop. May 26 Handling Native EXE Output Encoding in UTF8 with No BOMIf you are dealing with an native executable that outputs UTF8 with no BOM (byte order marker) you will find that PowerShell garbles the input. This is most likely an issue with how the .NET console code interprets the incoming byte stream. Without a BOM it isn’t exactly easy to determine the proper encoding for a stream of bytes. For example take the following simple native exe source code that is supposed to output this (BTW ignore the fact that the text says ‘ASCII’ – it is really UTF8): ASCII outputᾹ Contents of stdout.cpp: #include <stdio.h> If you pipe the output of this program into a PSCX utility called Format-Hex (alias is fhex), you can see the actual unicode byte stream that was created by .NET’s interpretation of the incoming byte stream.
ASCII outputᾹ The solution to this problem is to provide a hint to the .NET console functionality about the encoding of the incoming bytes. You can do this very simply:
ASCII outputᾹ And is as it should be. However this may seem somewhat counter-intuitive (it did to me) since the problem is with PowerShell/.NET “reading” console input and not writing it. Well one of the good folks on the PowerShell team pointed out to me that the Console OutputEncoding is probably inherited by child processes and a quick little experiment reveals this to be true. So by setting the OutputEncoding this determines how .NET encodes console output which helps PowerShell/.NET determine the correct encoding when reading in this information via console input. One last point on this approach is that you should stash the original value of [Console]::OutputEncoding and restore it after you’ve run a problematic exe like in this example. I’ve found that the C# compiler will crash if you run it in PowerShell with the [Console]::OutputEncoding set to UTF8. May 11 What’s in PSCX 2.0Some questions are coming up about the contents of PSCX 2.0. Here’s what in it: CMDLETS: FUNCTIONS: ALIASES: PROVIDERS: May 10 PSCX 2.0 Show-TreeOne issue with PowerShell providers is that only the Filesystem and Registry providers’ hierarchies are easily viewable using Windows Explorer and Regedit respectively. The other PowerShell providers are mostly without such a view. This is problematic for providers that supply configuration information like the WSMan provider. Without a lot of cd’ing around it is hard to get a “lay of the land” with respect to the various settings that are available. In Pscx 2.0, we set out to help with this problem by providing the equivalent of the old DOS tree.com routine. The command is called Show-Tree. If you have the final PSCX 2.0 bits installed try this from an elevated prompt: C:\PS> Show-Tree wsman: -ShowLeaf You can use this on most providers although some providers behave better than others under this command. Here’s a way to view registry entries e.g.: C:\PS> Show-Tree HKLM:\SOFTWARE\Microsoft\.NETFramework -Depth 2 -ShowProperty Give PSCX 2.0 a try and let us know what you think - good or bad! PSCX 2.0 ReleasedFinally! We’ve gotten PSCX 2.0 finished and released. A few notes about this release. It targets only Windows PowerShell 2.0 as it is module based. Also, the deployment of the PSCX 2.0 is xcopy. There is no installer. For more more info, check out the releases notes on the PSCX 2.0 download page. Please let us know if you find any issues. NOTE: Be sure to Unblock the ZIP before extracting it to your Modules folder. January 24 PowerShell Community Extensions 2.0 Beta ReleasedWe have released a new beta of PSCX that is complete module based and as such, only works with Windows PowerShell 2.0. You can have both 1.2 and 2.0 installed on the same system. You just alternate between Add-PSSnapin for 1.2 and Import-Module Pscx for 2.0. There is a new Test-Script cmdlet that checks for syntax errors in PowerShell scripts. There is also a few function Invoke-BatchFile that is very handy for importing environment variables created in a batch file. This is most handy for setting up your PowerShell environment for Visual Studio development e.g.: 1: Import-Module Pscx -DisableNameChecking2: $vcargs = ?: {$Pscx:Is64BitProcess} {'amd64'} {''} 3: $VS90VCVarsBatchFile = "${env:VS90COMNTOOLS}..\..\VC\vcvarsall.bat" 4: Invoke-BatchFile $VS90VCVarsBatchFile $vcargs
Give PSCX 2.0 a try and let us know what you think. Waiting for Out-GridView Windows to CloseThis came up on StackOverflow and thought it was worth reposting here. It shows how fancy you can get with low-level Win32 API calls using the new Add-Type cmdlet. The following code essentially checks for the existence of *any* window associated with the current process other than the main window. Any additional window like that created for Out-GridView will cause the script to wait until the last of these extra windows are closed. Note that Out-GridView windows are created as top level windows and their titles vary depending on the command text used to invoke the Out-GridView cmdlet. 1: $src = @' 2: using System; 3: using System.Diagnostics; 4: using System.Runtime.InteropServices; 5: using System.Threading; 6: 7: namespace Utils 8: { 9: public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam); 10: 11: public class WindowHelper 12: { 13: private const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; 14: private IntPtr _mainHwnd; 15: private IntPtr _ogvHwnd; 16: private IntPtr _poshProcessHandle; 17: private int _poshPid; 18: private bool _ogvWindowFound; 19: 20: public WindowHelper() 21: { 22: Process process = Process.GetCurrentProcess(); 23: _mainHwnd = process.MainWindowHandle; 24: _poshProcessHandle = process.Handle; 25: _poshPid = process.Id; 26: } 27: 28: public void WaitForOutGridViewWindowToClose() 29: { 30: do 31: { 32: _ogvWindowFound = false; 33: EnumChildWindows(IntPtr.Zero, EnumChildWindowsHandler, 34: IntPtr.Zero); 35: Thread.Sleep(500); 36: } while (_ogvWindowFound); 37: } 38: 39: [DllImport("User32.dll")] 40: [return: MarshalAs(UnmanagedType.Bool)] 41: public static extern bool EnumChildWindows( 42: IntPtr parentHandle, Win32Callback callback, IntPtr lParam); 43: 44: [DllImport("Oleacc.dll")] 45: public static extern IntPtr GetProcessHandleFromHwnd(IntPtr hwnd); 46: 47: [DllImport("Kernel32.dll")] 48: public static extern int GetProcessId(IntPtr handle); 49: 50: [DllImport("Kernel32.dll")] 51: [return: MarshalAs(UnmanagedType.Bool)] 52: public static extern bool DuplicateHandle( 53: IntPtr hSourceProcessHandle, 54: IntPtr hSourceHandle, 55: IntPtr hTargetProcessHandle, 56: out IntPtr lpTargetHandle, 57: int dwDesiredAccess, 58: bool bInheritHandle, 59: int dwOptions); 60: 61: [DllImport("Kernel32.dll")] 62: [return: MarshalAs(UnmanagedType.Bool)] 63: public static extern bool CloseHandle(IntPtr handle); 64: 65: [DllImport("Kernel32.dll")] 66: public static extern int GetLastError(); 67: 68: private bool EnumChildWindowsHandler(IntPtr hwnd, IntPtr lParam) 69: { 70: if (_ogvHwnd == IntPtr.Zero) 71: { 72: IntPtr hProcess = GetProcessHandleFromHwnd(hwnd); 73: IntPtr hProcessDup; 74: if (!DuplicateHandle(hProcess, hProcess, _poshProcessHandle, 75: out hProcessDup, 76: PROCESS_QUERY_LIMITED_INFORMATION, 77: false, 0)) 78: { 79: Console.WriteLine("Dup process handle {0:X8} error: {1}", 80: hProcess.ToInt32(), GetLastError()); 81: return true; 82: } 83: int processId = GetProcessId(hProcessDup); 84: if (processId == 0) 85: { 86: Console.WriteLine("GetProcessId error:{0}", 87: GetLastError()); 88: return true; 89: } 90: if (processId == _poshPid) 91: { 92: if (hwnd != _mainHwnd) 93: { 94: _ogvHwnd = hwnd; 95: _ogvWindowFound = true; 96: CloseHandle(hProcessDup); 97: return false; 98: } 99: } 100: CloseHandle(hProcessDup); 101: } 102: else if (hwnd == _ogvHwnd) 103: { 104: _ogvWindowFound = true; 105: return false; 106: } 107: return true; 108: } 109: } 110: } 111: '@ 112: 113: Add-Type -TypeDefinition $src 114: 115: Get-Process | Out-GridView 116: 117: $helper = new-object Utils.WindowHelper 118: $helper.WaitForOutGridViewWindowToClose() 119: 120: "Done!!!!"
Note the use of DuplicateHandle(). This was required because initially we don’t have permissions to ask for the process ID of the process handle returned from GetProcessHandleFromHwnd. During the handle duplication we can ask for the permission we need to get the process id. January 20 Windows PowerShell Localized Online HelpFresh from the PowerShell team: http://technet.microsoft.com/zh-cn/library/bb978526.aspx Enjoy! January 01 Windows PowerShell MVP Award for 2010Just got the notice today. Woohoo! I expect 2010 to be a banner year for PowerShell as Windows 7 spreads PowerShell out to more folks than ever before and as usual, I’ll do what I can to help folks grok PowerShell. December 06 JSON Serialization/Deserialization in PowerShellSince PowerShell is based on .NET and makes it easy to access .NET functionality, PowerShell can use JSON serializer that comes with .NET. The follow snippet of code shows how to deserialize a JSON string into an XML object and then how to take an XML object and serialize it to JSON; 1: Add-Type -Assembly System.ServiceModel.Web,System.Runtime.Serialization 2: 3: function Convert-JsonToXml([string]$json) 4: { 5: $bytes = [byte[]][char[]]$json 6: $quotas = [System.Xml.XmlDictionaryReaderQuotas]::Max 7: $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($bytes,$quotas) 8: try 9: { 10: $xml = new-object System.Xml.XmlDocument 11: 12: $xml.Load($jsonReader) 13: $xml 14: } 15: finally 16: { 17: $jsonReader.Close() 18: } 19: } 20: 21: function Convert-XmlToJson([xml]$xml) 22: { 23: $memStream = new-object System.IO.MemoryStream 24: $jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($memStream) 25: try 26: { 27: $xml.Save($jsonWriter) 28: $bytes = $memStream.ToArray() 29: [System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length) 30: } 31: finally 32: { 33: $jsonWriter.Close() 34: } 35: } 36: 37: $str = '{"fname":"John", "lname":"Doe", "age":42, "addr":{"city":"Gotham", "street1":"123 Guano Way", "state":"NY"}}' 38: 39: $xml = Convert-JsonToXml $str 40: $xml.root.fname 41: $xml.root.lname 42: 43: $json = Convert-XmlToJson $xml 44: $json
October 30 PowerShell - Find-PInvoke.ps1I had a need to find all PInvokes in an assembly. At first I thought about searching the source code since I had it but ran into various problems:
[Updated: 11-02-2009] I decided to go with the "reflection only load" approach to extract the PInvoke (DllImport) information. The script file has been updated to reflect (pun intended) this new and better approach. In fact, more data is gathered for each PInvoke including all of the values for the associated DllImportAttribute. Now to see if I can get this included in the next version of PSCX. It seems that the reflection only load is sensitive to assembly load failures. Once an assembly fails to load you pretty much have to start a new PowerShell session to try again. I'll keep looking into this. For what appears to be a really neat capability (ReflectionOnlyLoad) it has some unfortunate short-comings. Here is some sample output when run on the PSCX snapin dlls. PS> gci C:\Users\Keith\Pscx\Trunk\Src\Pscx\bin\Debug\Pscx*.dll | .\Find-PInvoke | DllImport: advapi32.dll Assembly MethodName TypeName DllImport: Fusion.dll Assembly MethodName TypeName DllImport: kernel32.dll Assembly MethodName TypeName October 29 PowerShell 2.0 – Accessing Different ProfilesJust ran across a new feature of PowerShell 2.0 that is convenient. Need the path to the various profile scripts on a system? Try this: PS> $profile.psextended | Format-List AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 To access individually you can use $profile.AllUsersAllHosts. psmdtag:variable Profile October 21 Windows PowerShell 2.0 String LocalizationOne of the lesser known features in PowerShell 2.0 is that it supports string localization and pretty simply I might add. Now for most developers and admins script localization probably isn’t going to be something you’ll worry about. However if you are providing PowerShell based solutions to an international audience this feature will come in very handy in terms of broadening your reach. I believe the driving force behind this feature’s inclusion in PowerShell is that a critical component of Windows 7 – the Windows Troubleshooting Platform and associated troubleshooting packs – use PowerShell scripts extensively. Obviously Windows is localized to the extreme so it stands to reason that the troubleshooting scripts, which can interact with the end user via text prompts, were required to be localized. Enough context. Let’s look at how localization works in PowerShell 2.0. First, the feature in PowerShell is referred to as “Data Sections” and is covered by the help topics:
Let’s start by creating our string table file. This is created as a .psd1 (data) file. In this case, we will call it messages.psd1 and its contents are simply: # Contents of .\messages.psd1 This is a bit odd looking for a “data” file but the gist is that the ConvertFrom-StringData cmdlet returns a ordinary hashtable. The string that ConvertFrom-StringData operates on has to be in a special format which is essentially one key/value pair per line where the key and value are separated by an “=”. The “key” is how you will reference the “value” (actual localized string) from your script. FWIW you could just have the psd1 file return a hashtable directly but then you have to quote each value. So the format above is a bit cleaner and more like a traditional string table file. Now at this point you could and might be tempted to do something like this in your script: $msgs = .\messages.psd1 But there is one tiny little problem - .psd1 files are not executable like .ps1 or .psm1 files are. Hey, that’s probably why they are called “data” files. :-) Obviously PowerShell must provide a way to load these files and that mechanism is the Import-LocalizedData cmdlet. It takes the path to a .psd1 file, loads it and then assigns the resulting hashtable to a variable name provided to the cmdlet. Let’s see an example of this: # Contents of test.ps1 The output of this script is: PS> .\test.ps1 You may be thinking that this seems like a pretty simple task, not worthy of requiring a dedicated cmdlet. However there is one very important piece of “non-trivial” functionality that the Import-LocalizedData cmdlet provides and that is it searches through various culture specific sub directories looking for a matching .psd1 file for the user’s culture. For those familiar with .NET development this is very similar to how the .NET binder looks through application’s base sub dirs for the appropriate satellite assembly for the user’s culture. Let’s see an example of how this works. First, let’s create a German version of our string resources and put the file in a sub dir titled de-DE. The name of this sub dir is important. The name reflects the <language>-<region> that the localized strings target. Here are the contents of .\de-DE\messages.psd1: # Contents of .\de-DE\messages.psd1 At this point our dir structure looks like this: .\test.ps1 Now I need to introduce a somewhat orthogonal but very handy function called Using-Culture that the PowerShell team blogged a long time ago. I have updated it for PowerShell 2.0 and I use it to effectively simulate running PowerShell scripts in different cultures. function Using-Culture ([System.Globalization.CultureInfo]$culture =(throw "USAGE: Using-Culture -Culture culture -Script {scriptblock}"), Now let’s try running out test.ps1 script under the German language/region: PS> Using-Culture de-DE { .\test.ps1 } Now that’s what I’m talking about! Script localization without requiring an advanced degree. Now, you might ask – what happens when somebody run’s in a culture that I have not localized for? Let’s see: PS> Using-Culture fr-FR { .\test.ps1 } When I listed the dir contents above I mentioned that the top-level messages.psd1 was the “fallback”. Essentially if PowerShell can’t find the specified data file for the current culture it will “fallback” to the top-level data file or .\messages.psd1 in this case (which is English). This may very well be a feature you never use but if you desire to reach a broad audience with your PowerShell 2.0 modules, consider pulling out your strings into a data file even if you only provide a data file for your native language. This gives others a much better chance of localizing your module into other languages for you! It’s Official - Windows 7 and Windows PowerShell 2.0 for Everyone!Congratulations to the Windows and Windows PowerShell teams for two very excellent releases. I’ve been using Windows 7 daily since January’s beta release and PowerShell 2.0 drops for even longer. Both products are destined to be smash hits in my humble opinion. I’m very excited about the new capabilities of PowerShell 2.0 and the fact that it’s a built-in and required component of Windows 7 means that the time when we can count on PowerShell “just being there” is getting closer. October 16 Windows PowerShell 2.0 Virtual Launch PartyI’m relaying this invite from Hal & Jonathan – hosts of the PowerScripting Podcast. Windows isn’t just about the GUI. Starting with Windows 7, you have built-in access to PowerShell version 2, an object-oriented scripting language and command shell. Please join PowerScripting Podcast hosts Jonathan Walz and PowerShell MVP Hal Rottenberg as they interview Distinguished Engineer Jeffrey Snover on launch day! Jeffrey is the chief architect responsible for PowerShell at Microsoft, and he’ll be covering what’s new with the tool and why every system administrator on the planet needs to be using it. If you’ve never attended PowerScripting Live, you are missing out on a great time. The show will be streamed live via Ustream, and viewers can chat with each other, as well as submit questions for the guest.
October 12 Windows PowerShell 2.0 and Windows Troubleshooting Platform PresentationTonight I gave a presentation on the new features in Windows PowerShell 2.0. I also demo how to create a Windows Troubleshooting Platform that is new in Windows 7. WTP uses PowerShell scripts to do the heavy lifting of detecting and resolving root causes i.e. problems that need fixing. I gave this presentation at the Northern Colorado.NET Special Interest Group. As promised, here are the presentation materials: slide deck and Start-Demo samples. September 02 PowerShell Community Extensions Makes Hanselman’s 2009 Ultimate Developer Tools ListBoth Windows PowerShell and PSCX made it into Scott Hanselman’s 2009 Ultimate Developer and Power Users Tool List for Windows. w00t! August 06 PowerShell Community Extensions 1.2 ReleasedWe have released PSCX 1.2 just in time for Windows 7 RTM availability on MSDN and TechNet. Thanks to those folks who tried out the beta for the past three months! And a huge thanks goes to PowerShell MVP Oisin Grehan who put a lot of effort into 1.2 and is the reason you have Read-Archive and Expand-Archive cmdlets among other new features.
The big enhancements for 1.2 are:
Major New Cmdlets
New Scripts
I hope you find as much utility in these cmdlets as I have. I use them everyday - of course! If you have any feedback please log it on the CodePlex project site on either the discussion forum or issue tracker. And if you download PSCX and are passionate about it (one way or the other), please write a review on the download page for 1.2.
Next up for PSCX is 2.0 which will most likely target only PowerShell 2.0 and come in Module form. August 03 Effective PowerShell Item 16: Dealing with ErrorsThere are several facets to the subject of errors in PowerShell that you should understand to get the most out of PowerShell. Some of these facets are error handling, error related global variables and error related preference variables. But the most fundamental facet is the distinction between “terminating” and “non-terminating” errors. Terminating Errors Terminating errors will be immediately familiar to software developers who deal with exceptions. If an exception is not handled it will cause the program to crash. Similarly if a terminating error is not handled it will cause the current operation (cmdlet or script) to abort with an error. Terminating errors and are generated by:
The gist of a terminating error is that the code throwing the terminating error is indicating that it cannot reasonably continue and is aborting the requested operation. As we will see later, you as the client of that code, have the ability to declare that you can handle the error and continue executing subsequent commands. Terminating errors that are not handled propagate up through the calling code, prematurely terminating each calling function or script until either the error is handled or the original invoking operation is terminated. Here is an example of how a terminating error alters control flow: PS> "Before"; throw "Oops!"; "After" Note that “After” is not output to the console because “throw” issues a terminating error. Non-terminating Errors Have you ever experienced the following in older versions of Windows Explorer? You open a directory with a large number of files, say your temp dir, and you want to empty it. You select the entire contents of the directory, press Delete and wait. Unfortunately some processes invariably have files open in the temp directory. So after deleting a few files, you get an error from Windows Explorer indicating that it can’t delete some file. You press OK and at this point Windows Explorer aborts the operation. It treats the error effectively as a terminating error. This can be very frustrating. You select everything again, press Delete, Explorer deletes a few more files then errors and aborts again. You rinse and repeat these steps until finally all the files that can be deleted are deleted. This behavior is very annoying and wastes your time. In an automation scenario, premature aborts like this are often unacceptable. Having a special category of error that does not terminate the current operation is very useful in scenarios like the one outlined above. In PowerShell, that category is the non-terminating error. Even though a non-terminating error does not terminate the current operation, the error is still logged to the $Error collection (discussed later) as well as displayed on the host’s console as is the case with terminating errors. Non-terminating errors are generated by:
Here is an example of how a non-terminating error does not alter control flow: PS> "Before"; Write-Error "Oops!"; "After" After Note the Write-Error command issues a non-terminating error that gets displayed on the host’s console then the script continues execution. Error Variables There are several global variables and global preference variables related to errors. Here is a brief primer on them:
The $Error global variable can be used to inspect the details of up to the last $MaximumErrorCount number of errors that have occurred during the session e.g.: PS> $error[0] | fl * -force PSMessageDetails : As the output above shows, errors in PowerShell are not just strings but rich objects. The object may be a .NET exception with an embedded error record or just an error record, The error record contains lots of useful information about the error and the context in which it occurred. The default output formatting of errors can be a bit hard to digest. The PowerShell Community Extensions come with a handy Resolve-Error function that digs through the error information and surfaces the important stuff e.g.: PS> Resolve-Error # displays $error[0] by default The $? global variable is handy for determining if the last operation encountered any errors e.g.: PS> Remove-Item $env:temp\*.txt -Recurse -Verbose In this case, the Remove-Item cmdlet only partially succeeded. It deleted two files but then encountered a non-terminating error. This failure to achieve complete success i.e. no errors, is indicated by $? returning False. Working with Non-Terminating Errors Sometimes you want to completely ignore non-terminating errors. Who wants all that red text spilled all over their console especially when you don’t care about the errors you know you're going to get. You can suppress the display of non-terminating errors either locally or globally. To do this locally, just set the cmdlet’s ErrorAction parameter to SilentlyContinue e.g. Remove-Item $env:temp\*.txt -Recurse -Verbose -ErrorAction SilentlyContinue For interactive scenarios it is handy to use 0 instead of SilentlyContinue. This works because SilentlyContinue is part of a enum and its integer value is 0. So to save your wrists you can rewrite the above as: ri $env:temp\*.txt -r -v –ea 0 Note that for a script I would use the first approach for readability. To accomplish the above globally, set the $ErrorActionPreference global preference variable to SilentlyContinue (or 0). This will cause all non-terminating errors in the session to not be displayed on the host’s console. However they will still be logged to the $Error collection. Setting the $ErrorActionPreference to Stop can be useful in the following scenario. If you misspell a command, PowerShell will generate a non-terminating error as shown below: PS> Copy-Itme .\_lesshst .\_lesshst.bak; $?; "After" False In this case, the misspelled Copy-Itme command failed ($? returned False) but since the error was non-terminating, the script continues execution as shown by the output “After”. If you are hard-core about correctness you can get PowerShell to convert non-terminating errors into terminating errors by setting $ErrorActionPreference to Stop which has global impact. You can also do this one a cmdlet by cmdlet basis by setting the cmdlet’s –ErrorAction parameter to Stop. The last issue to be aware of regarding non-terminating errors is that a Windows executable that returns a non-zero exit code does not generate any sort of error. The only action PowerShell takes is to set $? to False if the exit code is non-zero. There is no error record created and stuffed into $Error. In many cases, the failure of an external executable means your script cannot continue. In this case, it is desirable to convert a failure exit code into a terminating error. This can be done easily using the function below: function CheckLastExitCode { Note that Get-PSCallStack is specific to PowerShell v2.0. Invoke CheckLastExitCode right after invoking an executable, well at least for those cases where you care if an executable returns an error. This function provides a couple of handy features. First, you can specify an array of acceptable success codes which is useful for exes that return 0 for failure and 1 for success and is also useful for exes that return multiple success codes. Second, you specify a cleanup scriptblock that will get executed on failure. Handling Terminating Errors Handling terminating errors in PowerShell comes in two flavors. Using the trap keyword which is supported in both version 1 and 2 of PowerShell. Using try { } catch { } finally { } which is new to version 2. Trap Statement Trap is a mechanism available in other shell languages like Korn shell. It effectively declares that either any error type or a specific error type is handled by the scriptblock following the trap keyword. Trap has the interesting property that where ever it is declared in a scope, it is valid for that entire scope e.g.: Given the following script (trap.ps1): Invoking it results in the following output: PS> .\trap.ps1 Note that it doesn’t matter that the trap statement is after the line that throws the error. Also note that since the default value for $ErrorActionPreference is 'Continue', the error is displayed, logged to $Error but execution resumes at the next statement. Note: within the context of a trap statement, $_ represents the error that was caught. Another thing to consider is whether to use Write-Host or Write-Output to display text in the trap statement. The example above implicitly uses Write-Output. This has the benefit that the text can be redirected to a log file. The downside is that if the exception is handled and execution continues, that text will become part of the output for that scope which, in the case of functions and scripts, may not be desirable. If you want to execute cleanup code on failure but still terminate execution, we can change the trap statement to use the break keyword. Consider the following script: function Cleanup() {"cleaning up"} Note that the inner trap calls the Cleanup function but then propagates the error. As a result, the “Inner After” statement never executes because control flow is transferred outside the scope of the trap statement. The outer trap then catches the error, displays it and continues execution. As a result, the “Outer After” statement is executed. The interaction between the control flow altering keywords valid in a trap statement (break, continue and return), the $ErrorActionPreference variable if no control flow altering keyword is used and the final behavior is somewhat complex as is demonstrated by the table below: Trap Behavior:
* <object> is appended to the end of the trap scope’s output. All of the examples of trap shown above trap all errors. You may want to trap only specific errors. You can do this by specifying the type name of an exception to trap as shown below: trap [System.DivideByZeroException] { "Please don't divide by 0!"} If you want to execute different code for different errors, you can define multiple trap statements in your script: trap [System.DivideByZeroException] { "Please don't divide by 0!"}trap [System.Management.Automation.CommandNotFoundException] { "Did you fat finger the command name?" } If you define multiple trap statements for the same error type the first one wins and the others within the same scope are ignored. Try / Catch / Finally Version 2 of Windows PowerShell introduces try/catch/finally statements - a new error handling mechanism that most developers will be immediately familiar with. There are two main differences between trap and try/catch/finally. First, a trap anywhere in a lexical scope covers the entire lexical scope. With a try statement, only the script within the try statement is checked for errors. The second difference is that trap doesn’t support finally behavior i.e., always execute the finally statement whether the code in the try statement throws a terminating error or not. In fact, any associated catch statements could also throw a terminating error and the finally statement would still execute. You can fake finally behavior with trap by calling the same “finally” code from the end of the lexical scope *and* from the trap statement. Consider the Cleanup function from the earlier example. We want to always execute Cleanup whether the script errors or not. The example shown in the previous section using the Cleanup function works OK unless the Cleanup function throws a terminating error. Then you run into the issue where Cleanup gets called again due to the trap statement. This sort of cleanup is much easier to represent in your script using try/finally e.g.: function Cleanup($err) {"cleaning up"} "Outer Before" This example results in Cleanup always getting called whether or not the script in the try statement generates a terminating error. It also shows that you can mix and match trap statements with try/catch/finally. One last example shows how you can use catch to handle different error types uniquely: function Cleanup($err) {"cleaning up"} "Outer Before" The use of the finally statement is optional as is the catch statement. The valid combinations are try/catch, try/finally and try/catch/finally. In summary, PowerShell’s error handling capabilities are quite powerful especially the ability to distinguish between non-terminating and terminating errors. With the addition of the new try/catch/finally support in version 2.0 the important scenario of resource cleanup is easy to handle. August 02 Tail-File Cmdlet Coming in PSCX 1.2Occasionally I need to tail some very large log files over the network. In this scenario, the standard PowerShell approach: PS> Get-ChildItem *.log | %{ Get-Content $_ | Select –Last 1 } just isn’t practical for performance reasons. So the final drop of PSCX 1.2 will have a new cmdlet called Tail-File that is optimized for tailing the end of large (even huge) log files. Here’s a performance comparison of the two approachs: 19# measure-command { tail-file \\Keith-PC\C\*.txt -count 1 } Days : 0 20# measure-command {Get-ChildItem \\Keith-PC\C\*.txt | %{ Get-Content $_ | Select -Last 1 }} Days : 0 Milliseconds : 656 That is a speed-up of approximately 2500x. That is pretty significant especially if you need to do this to a number of large log files. For reference, the above test tailed two medium size log files (total size: 37.4 MB): -a--- 5/23/2009 6:33 AM 4173558 dirlist.txt Tail-File handles ASCII and Unicode encoding as well UTF8 as long as it contains only ASCII characters i.e. it will not choke on the UTF8 byte order mark. Oh yeah, it also supports active tailing (tail –f) via the Wait parameter. Use Ctrl+C to return control back to the console. July 17 A Simple Go Function to Simplify Navigating to Popular DirectoriesBefore PowerShell came along I had a number of doskey aliases set up like “gt” to go to the temp dir. I have since converted those aliases to a single g function (short for “go”): 1: function g($shortcut) { 2: $ht = @{3: bin = "C:\Bin"; 4: doc = "$([Environment]::GetFolderPath('MyDocuments'))"; 5: sys = "$env:SystemRoot\System32"; 6: t = "$env:Temp"; 7: win = "$env:SystemRoot"; 8: cf = "$env:CommonProgramFiles"; 9: pf = "$env:ProgramFiles"; 10: www = "$env:SystemDrive\inetpub\wwwroot"; 11: gac = "$env:SystemRoot\Assembly\GAC"; 12: tfs = "C:\Tfs" 13: clr = "$([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory())"; 14: } 15: 16: if ($shortcut) { 17: if (!$ht["$shortcut"]) { 18: throw "$shortcut isn't valid shortcut. Execute g with no params to see valid shortcuts." 19: } 20: cd $ht.$shortcut 21: }22: else { 23: "Valid shortcuts are:" 24: $ht.Keys | Sort | select @{n='Shortcut';e={$_}},@{n='Destination';e={$ht.$_}} 25: } 26: }
Usage is pretty simple. Execute g to see all shortcuts and the associated location: PS C:\> g Shortcut Destination To set-location to the wwwroot dir execute the following: PS C:\> g www It’s a trivial function but if you spend a lot of time at the PowerShell prompt, it (or something similar) is quite handy. May 22 PSCX Tips Part 2This is a continuation of PSCX Tips Part 1. Here are some more things you can do with the PowerShell Community Extensions. If you do .NET software development and partially strong name your assemblies then you know that at some point in your official build process you need to finish the strong-naming process. When we have done this, we cycle through all the exes and dlls in a common output dir and apply the full strong name. Problem is that we have some native binaries mixed in with the managed binaries. So we need some quick way to test if a file is a managed assembly. This is where Test-Assembly comes in handy: PS> Get-ChildItem | Where {$_ –match '\.(dll|exe)$' –and (Test-Assembly $_)} | On 64-bit Windows you may want to know whether a binary is a 32-bit or 64-bit binary. That’s easy with Get-PEHeader: PS> Get-PEHeader .\wordpad.exe Type : PE64 Need to test if the current user is elevated on Vista or Windows 7? Use Test-UserGroupMembership e.g.: PS> Test-UserGroupMembership -GroupName Administrators Need to know what the 8.3 filename is for a file? Use Get-ShortPath e.g.: PS> Get-ShortPath '.\Windows Azure SDK' Need a touch like utility to change a file’s various time fields? Try Set-FileTime e.g.: PS> Set-FileTime .\test.csv -Modified (Get-Date).AddDays(-2) Need to compute the hash for a string or an entire file using various algorithms e.g.: PS> "hello world" | Get-Hash Algorithm: MD5 Path : PS> Get-Hash .\uszip.wsdl -Algorithm SHA1 Algorithm: SHA1 Path : C:\Users\Keith\uszip.wsdl Need to convert between different OS style line endings in files? Check out these cmdlets;
Need to convert from or to Base64? Try out the ConvertTo-Base64 and ConvertFrom-Base64 cmdlets e.g.: PS> [byte[]](1..255) | ConvertTo-Base64 When parsing legacy exe text, do you ever need to skip either the first couple of lines or perhaps the last line (or both)? Skip-Object is very convenient here because you don’t need to know the length of the sequence you are dealing with. Here’s an example: PS> 1..10 | Skip-Object -First 2 -Last 1 -Index 4,6 That’s enough for this post but there’s still plenty more in PSCX. Stay tuned. May 20 PSCX TipsWe recently released a beta of the PowerShell Community Extensions that supports PowerShell V2 in addition to V1. This version also supports 64-bit versions of Windows. The primary purpose of PSCX is to flesh out the functionality of PowerShell such that tools like cygwin and MKS Toolkit aren’t needed. We aren’t completely there with PSCX yet but there is quite a bit of useful functionality in PSCX. Here are some examples. Enhanced CD function has browser like backwards and forwards history: PS> cd $pshome;cd $pscx:home;cd $pscx:ScriptsDir;cd~ # Directory Stack: Sending PowerShell output to the clipboard: PS> Get-Process | Out-Clipboard Inspecting the contents of a file ala od.exe (octal dump): # View the first 16 bytes of powershell.exe Address: 0 1 2 3 4 5 6 7 8 9 A B C D E F ASCII # Using the fhex alias to inspect a text file to see if it has the UTF-8 BOM Address: 0 1 2 3 4 5 6 7 8 9 A B C D E F ASCII Formatting XML: # Ever have an XML string display as one long line, try this out Testing XML for well-formedness and against a schema: PS> "<a><b><c><d/></c></b></a>" | Test-Xml Applying a XSL transform to a file: PS> Convert-Xml My.xml –XsltPath My.xsl –EnableScript There is a lot more functionality in PSCX such as the ability to create, read and expand ZIP and TAR files. But that is enough of a teaser for this post. Stay tuned for more info on what’s in PSCX. May 14 PSCX 1.2 Beta AvailableLast night we released a beta of the PowerShell Community Extensions 1.2. The release supports Windows PowerShell V2 and has better support for 64-bit Windows. PowerShell MVP/Rockstar Oisin Grehan has added two very useful cmdlets to this release: Read-Archive and Expand-Archive which works not only on TAR and ZIP files but also on ISO files. Give it a spin. You can download it here. Be sure to let us know if you run into any problems either via the PSCX discussion forum or issue tracker. BTW, there are two known issues on x64 Windows. The cmdlets Get-PEHeader and Test-Assembly don’t work. After a week or so, we’ll look at officially releasing 1.2. May 02 PowerShell V2 Remoting on Workgroup Joined Computers – YES It Can Be DoneThere are a number of extra steps to take to get V2 remoting to work on workgroup joined computers like the ones in your home – unless you’re running a DC at home (sick puppy). First up, is a registry setting that makes V2 remoting work on workgroup computers: PS> new-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -propertyType DWord -value 1 Be sure to run this from an elevated prompt. Then from that same elevated prompt, execute the following cmdlet: PS> Enable-PSRemoting To verify that remoting is working on this PC by executing the following command (also from an elevated prompt): PS> Enter-PSSession localhost If remoting is working you should get a prompt something like this: [localhost]: PS C:\Users\Keith\Documents> Note: If you are trying to get PowerShell 2.0 remoting working on an XPMode virtual machine (you know the one you get for free with Windows 7 Pro or higher) then you need to enable Classic share & security model for local accounts like so:
Now try re-running Enable-PSRemoting and it should work. Finally, on the PC(s) that you want to use to initiate remoting, execute this command so that all the local target computers are trusted: PS> set-item wsman:localhost\client\trustedhosts -value * Now, at this point you should be able to enter a new pssession to a remote computer. Note that you don’t have to be in an elevated prompt to do this. However you will need to pass your credentials to the remote computer like so: PS> $cred = Get-Credential # Type in the username/password for an admin account on the remote PC Credential Delegation One other area that can bite you is credential delegation. Here is the scenario. Say you remote into a PC and from that PC you want to access files on another PC via a UNC share. As things stand now, you run into the following error: [mediacenterpc]: PS C:\Users\Keith\Documents> dir \\homeserver\photos To fix this you have to enable credential delegation (second hop) and use CredSSP authentication. First on the target/remote computer you need to run this in an elevated prompt: Note that you can’t run this from a V2 remoting session (you’ll get “access is denied”): PS> Enable-WSManCredSSP –Role Server Now on your client/local computer execute the following from an elevated prompt for each remote computer you need credential delegation for: PS> Enable-WSManCredSSP –Role Client –DelegateComputer <computer_name> We are close but there is one last step and it requires a tweak via the global policy editor. Run gpedit.msc and navigate to Computer Configuration –> Administrative Templates –> System –> Credential Delegation as shown below: Open up the “Allow Delegating Fresh Credentials with NTLM-only Server Authentication” setting. Enable the setting and then click on the “Show…” button to add a server to the list. I added mine like so: Press OK and then press the “Apply” button on the previous dialog to apply the setting. Now credential delegation will work for that configured remote computer. Note that when you enter a new PSSession you have to use CredSSP authentication as shown below: PS> Enter-PSSession MediaCenterPC -Cred $cred -Authentication CredSSP Directory: \\HomeServer\Software Mode LastWriteTime Length Name Note that from the remoting session on MediaCenterPC, I can now see the files shared from my Windows Home Server. Woohoo! It isn’t exactly as straight forward as I would like but it can be done. |
Public folders
|
||||||||||||||||||||||||||||||
|
|