none
Trimming Strings - Microsoft, please change your documentation RRS feed

  • General discussion

  • Good afternoon, one of the PowerShell tips in the technet article “Windows PowerShell Tip of the Week” (https://technet.microsoft.com/en-us/library/ee692804.aspx) is misleading and I’d like to suggest an alternative wording/method in the specific section below:

    Bonus Tip: Removing Characters From the Beginning of a String

    Consider a folder containing a bunch of files similar to this (a sight familiar to digital camera users):

    Copy

    HIJK_111112.jpg
    HIJK_111113.jpg
    HIJK_111114.jpg
    HIJK_111115.jpg

    Suppose you want to remove the HIJK_ prefix from each of these file names. How can you do that? Well, here’s one way, using a string value instead of a file system object and file name property (although the approach is exactly the same):

    Copy

    
    
    
    
    $d = "HIJK_111112.jpg"
    $e = $d.TrimStart("HIJK_")

    For the above example, I would hesitate to introduce trim to readers in this way. Without explaining how trim works this could lead them to a dangerous assumption that TrimStart is considering “HIJK_” as a pattern when really its considering each character individually when trimming and only stopping when it reaches the first non-matching character in the string. The best use case for trim in my opinion is removing spaces from the start, end, or both sides of a string. Beyond that things can get dangerous, and I would suggest a method less prone to error when looking to remove a pattern such as a specific word or ordered prefix/suffix.

    The example below illustrates how you could get into trouble with the method described in the article if you don’t know the details of how TrimStart works:

    $d = "IKJ_KJJKL__111112.jpg"

    $e = $d.TrimStart("HIJK_")

    Results in $e equaling:

    111112.jpg

    I would suggest explaining how trim works a little more or offer a better solution to trimming a pattern from the beginning of a string utilizing a Replace with a dash of Regex rather than a TrimStart:

    $d = "HIJK_111112HIJK_.jpg"

    $e = $d -replace "^HIJK_", ""

    Results in $e equaling:

    111112HIJK_.jpg

    The ^ indicates the start of a string. In my opinion replace is a much safer solution to the problem proposed in the example.

    Thank you for your time, consideration, and all the help you’ve given me with your articles over the years.

    Friday, June 9, 2017 5:32 PM

All replies