none
Using split() to get LAST field of a string

    Question

  • Hi people

    I'm using the following (crude) method of getting a line from a block of text to extract the Primary Host Header from IIS based on W3SVC id. At the moment I'm doing this;

    $server = "192.168.0.1"
    $iiswebQuery = iisweb /query /s $server
    [string]$thisSiteName = $iiswebQuery | Select-String -pattern "W3SVC/100"

    Which gives a nasty-as-you-like string full of whitespace. So, we'll get rid of that;

    [string]$thisSiteName = $iiswebQuery | Select-String -pattern "W3SVC/100" |  %{$_ -replace '  *', ' '}

    Which gets rid of the multiple spaces and creates a string I can split. However, I want the last field which, depending on how many spaces are in the IIS site name, can vary in index. So, is there any way I can use Split() to get me the *last* field of the string?

    Yes, I know this is awflulness at its most, but I don't know how to query IIS through Powershell directly so I'm bodging the thing together.

    Any solutions (or complete alternatives) would be much appreciated. It needs to be able to run remotely rather than on localhost.

    Cheers muchly.
    O.
    Monday, May 19, 2008 4:09 PM

Answers

  • As soon as you use split, an array is created of the results.  If you just need the last "section":

    PSH>$test="some long string with spaces"
    PSH>$test.split()[-1]
    spaces
    PSH>

    Marco
    Wednesday, May 21, 2008 12:22 PM

All replies

  • I had a thought about this, I could address it by index directly if I know how many spaces were in the string. 7 spaces would equal 8 fields, therefore I could reference Music.

    Which begs the question, is there any way of counting how many iterations of a character (space, in this case) are in a string?

    Cheers
    O.
    Tuesday, May 20, 2008 11:42 AM
  • As soon as you use split, an array is created of the results.  If you just need the last "section":

    PSH>$test="some long string with spaces"
    PSH>$test.split()[-1]
    spaces
    PSH>

    Marco
    Wednesday, May 21, 2008 12:22 PM
  • $thisSiteName = $iiswebQuery | Select-String -pattern "W3SVC/100" |  %{$_ -replace '  *', ' '}

    new-item -name tmp.txt -type file -force
    $thisSiteName -split " " > tmp.txt
    $AllFields = get-content -path ./tmp.txt
    $FirstField = $AllFields[1] 

    #All Other Fields are available, too

    $LastField = $AllFields[($AllFields).Length]

    Wednesday, September 25, 2013 2:32 AM