Powershell Regex and multiple matches

Hi all, 
I have been messing with powershell for a while now, but this regex challenge has got me stumped.
I have a block of text, with is an output from a previous command, the variable is called $data
The contents look like:
Host : 10.0.0.1
Output : Listening on eth1
# Host name (port/service if enabled) last 2s last 10s last 40s cumulative
1 LOCALPC.internaldomain.net => 79.1Kb 79.1Kb 79.1Kb 19.8KB
www.awebsite.com.au <= 3.99Mb 3.99Mb 3.99Mb 1.00MB
Total send rate: 83.3Kb 83.3Kb 83.3Kb
Total receive rate: 3.99Mb 3.99Mb 3.99Mb
Total send and receive rate: 4.08Mb 4.08Mb 4.08Mb
Peak rate (sent/received/total): 83.3Kb 3.99Mb 4.08Mb
Cumulative (sent/received/total): 20.8KB 1.00MB 1.02MB
============================================================================================
ExitStatus : 0
I am trying to extract the two host names from that block of text, one will always be a hostname ending in internaldomain.net the other one can either be a host name or IP address. They may appear in alternate orders as well.
I can get a single match without an issue:
if ($data -match "(?<=\s).*?(?=.internaldomain)") {
$pcname = $matches[0].Trim()
or
if ($data -match "\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3} (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b") {
$externalip = $matches[0].Trim()
if ($data -match "([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?") {
$externalhost = $matches[0].Trim()
But I can't for the life of me extract the second match.
Anyone got some pointers in how I can extract both matches into strings?
Cheers,
Pazu

Thank you very much mjolinor, greatly appreciated and is all working now, one last question, the regex seems to be matching the number 1 prior to the first proper match, I'm not good enough with regex yet to understand why.
An example of the data match on the one is:
Host : 10.0.0.1
Output : Listening on eth1
# Host name (port/service if enabled) last 2s last 10s last 40s cumulative
1 Work-iPhone.internal.net => 3.57Kb 3.57Kb 3.57Kb 915B
11.111.239.45 <= 2.81Kb 2.81Kb 2.81Kb 719B
Total send rate: 3.57Kb 3.57Kb 3.57Kb
Total receive rate: 2.96Kb 2.96Kb 2.96Kb
Total send and receive rate: 6.54Kb 6.54Kb 6.54Kb
Peak rate (sent/received/total): 3.57Kb 2.96Kb 6.54Kb
Cumulative (sent/received/total): 915B 759B 1.63KB
============================================================================================
ExitStatus : 0
In this sample data, the second line ending in cloudfront doesn't get matched, but it matches 'Total'?
Host : 10.0.0.1
Output : Listening on eth1
# Host name (port/service if enabled) last 2s last 10s last 40s cumulative
1 TARDIS.mashdinternal.net => 2.50Kb 2.50Kb 2.50Kb 640B
server-54-240-177-103.syd1.r.cloudfront <= 169Kb 169Kb 169Kb 42.2KB
Total send rate: 2.66Kb 2.66Kb 2.66Kb
Total receive rate: 169Kb 169Kb 169Kb
Total send and receive rate: 172Kb 172Kb 172Kb
Peak rate (sent/received/total): 2.66Kb 169Kb 172Kb
Cumulative (sent/received/total): 681B 42.2KB 42.9KB
============================================================================================
ExitStatus : 0
Any ideas?
Cheers,
Pazu

Similar Messages

  • Regular expressions with dates and multiple matches

    I am currently attempting to automate modifying start and end dates within a .config file via powershell but I am having issues identifying the regular expression for the end date section since both are on the same line in the file. Below is the string that
    I want to change.
    Sometimes the dates are blank and sometimes the dates are filled in.
    Dates are always in the same format (yyyy-MM-dd hh:mm).
    I also want to note that there are multiple instances of 'StartDate="" EndDate=""' for other applications throughout the same config file so I cannot limit the expression to not include the App name. 
    I do not want to limit the search to a line number since there are instances where admins will add an extra space in the config file that may throw off the line number.
    I want to replace the dates or lack there of in their respective spots on the line below via powershell:
     <App name="TestApp" StartDate="2012-03-22 13:30" EndDate="">
    I am successfully able to use 
    $startRegex = '(?<=<App name="TestApp" StartDate=")([^"]*)'
    to replace the StartDate but I can't seem to single out the EndDate with regular expression. What expression can I use to have it ignore what is in the quotations after StartDate and only pay attention to the EndDate value?
    Below is a snippet: 
    $path = d:\inetpub\website\app.config
    $startRegex = '(?<=<App name="TestApp" StartDate=")([^"]*)'
    $starttime = (get-date).ToString("yyyy-MM-dd hh:mm")
    (gc $path) -replace $startregex, $starttime | set-content $path
    I want to accomplish the same for EndDate.
    Thanks in advance!

    If you do this with XML it will be painless and less prone to error.
    $n=$xml.SelectSingleNode('//App[@name="TestApp"]')
    $n.StartDate=$newstartdate
    $n.EndDate=$newenddate
    $xml.Save($filename)
    \_(ツ)_/

  • How do icloud and itunes match work with multiple libraries?

    How do icloud and itunes match work with multiple libraries?

    This forum is for troubleshooting compatibility issues between Macs and Windows, not iTunes. You'll probably want to repost your question in the iTunes discussions:
    http://discussions.apple.com/category.jspa?categoryID=150

  • ITunes match and multiple accounts

    Do any of you know whether having multiple Apple ID's and iTunes match will interfere with App Store purchases?
    Let me eleborate.  We have 2 iPhone 4s in the family each with their own apple ID, so obviously some music is purchased by both and some apps are purchased by both.  Both devices synchronize with a single library in iTunes.  My fear is that when I flip the switch on iTunes Match it will lock me or the other individual out from the purchases that we share on our devices and result in a nightmare.  From what I understand once you log into iTunes match you cant log into another account for 90 days.  Would appreciate some clarification if any of you know.
    Thanks for your input.

    MacUserAE --- based on my experience over the last few days, I would urge you to STAY AWAY from iTunes Match until Apple can better support the concept of multiple Apple ID's sharing content. After purchasing the Match upgrade about a week ago, I've spent perhaps 20 hours of my home life dealing with Match-related issues.  What you are fearful of - that you will somehow be locked out of your ID and your purchased content - is exactly what happened to me.
    I also thought that iTunes Match would be a good way to consolidate and then share music/video/apps between family members. I purchased the service with 2 goals in mind:  share content in my house via a Mac Mini server, and also "consolidate" the content my wife and I had purchased across three separate Apple IDs. I am not a technology novice.  I read the various online boards, read the Apple support pages, and based on what I read was convinced that Apple's product would deliver exactly the benefits I was looking for.
    I was wrong. 
    Apparently I did not migrate or associate my hardware (2 notebooks & a mini home server) in an Apple-approved sequence.  After putting about 10 hours into the project, I discovered that I had "used up" my computer's associations and could no longer download previously purchased items.  I am now missing 1000's of  purchased iTunes songs and videos.  I am not permitted to download or recover them until the 90-day "timer" runs out on each of my computers.  (Currently 84 days & counting). Ironically, I have an exceptionally "clean" and easy music collection: I have literally no shared/ripped/illegal content, as all of my media files were either uploaded from a purchased CD or purchased through iTunes.
    When I contacted Apple for support, I encountered a steady stream of suspicion and poor/misleading information from the different support reps I spoke to, each of whom seem to working independently. Support is apparently by Chat only, and much of the dialog seems canned, or pre-written.  For eample, the last support rep I dealt with first described his own experience setting up match using these pre-written cut & paste "snippets" that had obviously been prepared earlier, as they did not actually address the questions I was asking. Later in our encounter, he seemed to forget what he had already "pasted" and he wrote (in real-time) that he had actually not had any first-hand experience with the product.
    Discouraging all around.

  • Regex replacing multiple characters in string.

    I have been working through the Java regex tutorial and tried to modify one of the programs for my own use. Basically, I want to take a string and convert the chatracters A to T, T to A, C to G and G-C.
    I produced the rather crude program below, but of course it doesn't work. A could be converted to T and back again before the program terminates.
    I know that the code to do this correctly is probably quite complex, so could anyone point me in the direction of a tutorial which will help me to do this?
    This aside, I take it that if I am looking for multiple matches of characters which won't give the problem already indicated above, my code is too bloated anyway. Say, for example, instead of wanting to replace A to T, T to A, C to G and G-C, I wanted to replace dog-cat, horse-donkey - lion, tiger , cat-mouse. My code will work for this, but I am sure that it could be compressed a lot. Surely I would not need all the lines of code to do this?
    Thanks for any help,
    Tim
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    import java.io.*;  // needed for BufferedReader, InputStreamReader, etc.
        /** A Java program that demonstrates console based input and output. */
         class dna {
            // Create a single shared BufferedReader for keyboard input
            private static BufferedReader stdin =
                new BufferedReader( new InputStreamReader( System.in ) );
            // Program execution starts here
            public static void main ( String [] args ) throws IOException
                // Prompt the user
                System.out.print( "Type your DNA sequence: " );
                // Read a line of text from the user.
                String DNA = stdin.readLine();
                DNA = DNA.toUpperCase();
                String DNA2 = DNA;
                //calculate reverse complement
                Pattern A = Pattern.compile("A");
                Pattern T = Pattern.compile("T");
                Pattern C = Pattern.compile("C");
                Pattern G = Pattern.compile("G");
                Matcher AA = A.matcher(DNA);
                DNA = AA.replaceAll("T");
                Matcher TT = T.matcher(DNA);
                DNA = TT.replaceAll("A");
                Matcher CC = C.matcher(DNA);
                DNA = CC.replaceAll("G");
                Matcher GG = G.matcher(DNA);
                DNA = GG.replaceAll("C");
                // Display the input back to the user.
                System.out.println( "DNA input             : " + DNA2);
                System.out.println ("Complementary sequence: " + DNA);
        }

    TimM wrote:
    Thanks a lot!!! Can't believe you managed all that with so few lines of code.You're welcome.
    Must be great to know what you are doing :-)
    Thanks again,
    TimAfter being a bit more familiarised with the methods of String, you'll be able to do this in no time, I'm sure!

  • HT4137 iCloud setup with one Apple ID and multiple devices

    iCloud setup with one Apple ID and multiple devices

    What, exactly, are you trying to do? You can use the same iCloud account on as many devices as you want, as long as you don't turn on iTunes Match. Once you turn on Match, you're limited to 10 devices total.
    Is this what you want to do...same iCloud account, but different iTunes/App store accounts on each device? If so, you can do that also.

  • I the cloud and itunes match. Some songs have the "waiting" icon next to them but are unable to upload and instead of determing them ineligible itunes continues to try to upload that song and never gets to the rest of the list.

    I have  icloud and itunes match and most of my songs have been uploaded to the cloud. Some songs still have the "waiting" icon next to them and when I turn itunes match on they neither upload nor are they determined ineligible. My computer will literally spin its wheels for hours trying to upload the same song. Additionally, I uploaded an audiobook disc on my computer and 3 of the 11 tracks are still waiting to be uploaded???

    The exclamation mark happens if the file is no longer where iTunes expects to find it. Possible causes are that you or some third party tool has moved, renamed or deleted the file, or that the drive it lives on has had a change of drive letter. It is also possible that iTunes has changed from expecting the files to be in the pre-iTunes 9 layout to post-iTunes 9 layout,or vice-versa, and so is looking in slightly the wrong place.
    Select a track with an exclamation mark, use Ctrl-I to get info, then cancel when asked to try to locate the track. Look on the summary tab for the location that iTunes thinks the file should be. Now take a look around your hard drive(s). Hopefully you can locate the track in question. If a section of your library has simply been moved, or a drive letter has changed, it should be possible to reverse the actions.
    Alternatively, as long as you can find a location holding the missing files, then you should be able to use my FindTracks script to reconnect them to iTunes .
    If the missing files just can't be found then, assuming you are in region where you are permitted multiple downloads of your audio purchases, delete the current enties and download again from your purchased history.
    tt2

  • AC 5.3  Logical systems and multiple Physical systems

    HI all:
    We have set up a Logical System, and then have hooked up 2 Physical systems to it.  Based on the documentation from SAP, the rule set (and the way we set it up) is at the Logical system level. 
    Physical system #1 is reporting the correct results, however, Physical system #2 results are not complete.  My understanding is that both Physical systems should be drawing from the rule set based in the Logical system.
    Results:  Physical system #1 - correctly identifies 10 risks
                  Physical system #2 - incorrectly only identifies 5 of the expected 10 risks.
    Role assignment to user is exactly same, authorizations are exactly the same.  The User/Role/Profile Full Sync has been repeated as part of troubleshooting.
    Has anyone experienced this?  I'm looking for ideas/options on where to investigate why the results are different.
    Thanks
    Margaret

    HI:
    Thanks for answering!!  I'm having trouble understanding the answers, sorry.
    When you have a logical system...you upload the rules once to that system, and generate them.  Then when you set up a physical system and hook it up to the logical system...the 1st, 2nd or 3rd physical system....they all use the same ruleset.  The whole concept (as I understand) is that the use of Logical and Physical systems...and putting the rule set on the Logical system so you don't have to worry about one rule set taking precedence over another, is an advantage, if this is possible (ie: we don't have multiple rule sets).
    Where should I be checking that the risks are defined properly?  The rule set is the delivered one from SAP.  The functions and risks match what we had (plus more) in the CC 4.0 system.
    The first physical system we set up (example: Development) works fine, and all regular SoD risks are coming up as expected.  When we added another system (example: Test)...the results of SoD analysis were incomplete. 
    Does that help clarify?  Perhaps I'm just missing something?
    Margaret
    Edited by: Margaret Sokolov on Apr 28, 2009 4:34 PM

  • I have mulitple copies appearing on my ipad after using icloud and itunes match, how do I get only 1 copy to appear?

    I am new to the Ipad, I just got the Ipad with retina display in and only have a 16gb memory. I wanted to use Icloud for my music and other items, but when I started using Icloud and Itunes match, my Ipad has up to 3 of the same song listed on the song list. and will repeat when I am listening to my music. I was wondering how I can get those multiple copies go away to just 1.

    Hi,
    Read this user tip Recover your iTunes library from your iPod or iOS device
    Does it help?
    Jim

  • Cisco ISE - What does "Multiple Matched Rule Applies" mean?

    Hi,
    In Cisco ISE authroiztion policy configuration, what does the option "multiple matched rule applies" mean? I can understand the "first matched rule", but in "multiple matched rule" how is the "permissions picked if multiple rules match? Or, what is the logic involved in picking up the permissions, if multiple rules are matched in authorization policy.
    No where in cisco document I see any explaination for this.
    Would appreciate if any one can point me to  a document or explain me the login in selecting the persmissions if multiple rules are matched. Also, what would the use-case for this?
    Thanks and Regards,
    Mohan

    I agree with tarik & also this might be helpful for you:
    An authorization policy can  consist of a single rule or a set of rules that are user-defined. These  rules act to create a specific policy. For example, a standard policy  can include the rule name using an If-Then convention that links a value  entered for identity groups with specific condition(s) or attributes to  produce a specific set of permissions that create a unique  authorization profile. There are two authorization policy options you  can set:
    •First Matched Rules Apply
    •Multiple Matched Rule Applies
    These two options direct Cisco ISE  to use either the first matched or the multiple matched rule type  listed in the standard policy table when it matches the user's set of  permissions. These are the two types of authorization policies that you  can configure:
    •Standard
    •Exception
    Standard policies are policies  created to remain in effect for long periods of time, to apply to a  larger group of users or devices or groups, and allow access to specific  or all network endpoints. Standard policies are intended to be stable  and apply to a large groups of users, devices, and groups that share a  common set of privileges.
    Standard policies can be used as  templates in which you modify the original values to serve the needs of a  specific identity group, using specific conditions or permissions to  create another type of standard policy to meet the needs of new  divisions, or groups of users, devices, or groups in your network.
    By contrast, exception policies  are appropriately named because this type of policy acts as an exception  to the standard policies. Exception polices are intended for  authorizing limited access that is based on a variety of factors  (short-term policy duration, specific types of network devices, network  endpoints or groups, or the need to meet special conditions or  permissions or an immediate requirement).
    Exception policies are created to  meet an immediate or short-term need such as authorizing a limited  number of users, devices, or groups to access network resources. An  exception policy lets you create a specific set of customized values for  an identity group, condition, or permission that are tailored for one  user or a subset of users. This allows you to create different or  customized policies to meet your corporate, group, or network needs.
    http://www.cisco.com/en/US/docs/security/ise/1.0/user_guide/ise10_authz_polprfls.html

  • Best way to ensure combinations from the ValidationSet parameter attribute are processed correctly in PowerShell without using multiple IF statements?

    I have an advanced function I have been working on that looks something like this:
    Function Do-Something
    [cmdletbinding()]
    Param
    [Parameter(Mandatory=$true,
    [ValidateSet('Yes', 'No', 'Y', 'N', IgnoreCase = $true)]
    [string[]]$Param1,
    [Parameter(Mandatory=$true,
    [ValidateSet('Yes', 'No', 'Y', 'N', IgnoreCase = $true)]
    [string[]]$Param2,
    [Parameter(Mandatory=$true,
    [ValidateSet('Yes', 'No', 'Y', 'N', IgnoreCase = $true)]
    [string[]]$Param3
    Begin {}
    Process
    My question is, how do I get the values such as "Yes", "Y", "No", and "N" that's located in the [ValidateSet()] validation attribute processed correctly without having to use multiple "If" and "ElseIf"
    statements. 
    For instance, I want to avoid the following, because I know there is a faster and more efficient way (less typing) to do it:
    If ($param1 -match "Yes" -or "Y" -and $param2 -match "Yes" -or "Y" -and $param3 -match "Yes" -or "Y")
    #Do something here
    ElseIf  ($param1 -match "No" -or "N" -and $param2 -match "Yes" -or "Y" -and $param3 -match "Yes" -or "Y")
    #Do something
    I was reading that splatting may help me here, but I am new to the splatting technique and need some help with this one.
    I appreciate any help that anyone can offer. 
    Thanks

    Is this what you are trying to ask how to do?  Your posted script is written incorrectly and will not work at all. 
    Function Do-Something{
    [cmdletbinding()]
    Param (
    [Parameter(Mandatory=$true)]
    [ValidateSet('Yes','No','Y','N')]
    [string]$p1,
    [Parameter(Mandatory=$true)]
    [ValidateSet('Yes','No','Y','N')]
    [string]$p2
    Begin{
    Process{
    # parse the strings to booleans
    $p1a=if($p1 -match 'Yes|Y'){$true}else{$false}
    $p2a=if($p2 -match 'Yes|Y'){$true}else{$false}
    if($p1a){Write-Host 'P1 is good' -ForegroundColor green}
    if($p2a){Write-Host 'P2 is good' -ForegroundColor green}
    if($p1a -and $p2a){
    Write-Host 'All conditions met' -ForegroundColor green
    }else{
    Write-Host 'Conditions not met' -ForegroundColor red
    PS C:\scripts> Do-Something Y n
    P1 is good
    Conditions not met
    PS C:\scripts> Do-Something n n
    Conditions not met
    PS C:\scripts> Do-Something y y
    P1 is good
    P2 is good
    All conditions met
    This handles case and creates a tracking Boolean fo reach parameter so you can just build simple logic.
    ¯\_(ツ)_/¯

  • Multiple matches issue

    Strange issue with voice dialing finds a specific multiple match. I have an entry for "Mom" and one for "Mom - France". When I say "Call Mom" it says there are multiple entries and lists the above. When it beeps for me to speak again and I say "Mom" it always says "Calling Mom - France".
    I never mention "France", I speak clearly, and for all other numbers it recognises me fine. If there are multiple numbers for one person (home, mobile etc) it recognises my choice with no problems. So why mis-hear this one with an extra word?

    Not a direct answer but a workaround. I presume these are for the same people just different geographical locations.
    Combine "Mom - France" into the Mom contact by adding the France number after the first number. Label it "France" so when you say "Call Mom" it will say something like, "Mobile or France?". Or you could just say "Call Mom Mobile" or "Call Mom France".
    -SM

  • Regex fails to match, so it reports closest match

    Hi Guru's,
    I am using the regex API to match 2 lines of a message. If the match fails the 2 lines are reported to the user so they can see what has failed. Unfortunately the lines I am comparing are very long. (1000+ chars) So the user needs an indication of exactly what has failed.
    I was wondering if it is possible to use get a regex's closest match. So if whilst parsing, the regex managed to match 250/1000 characters I could tell user to start looking around character 250 for differences in the message.
    I have had a good google and can't find out how to do this, I have also quickly looked at the ORO perl5 api documentation, but cant find any code that implements this.
    Any help would be appreciated. thanks.

    I don't know of a way to do this, you could look into ParsePosition, but I don't know if you'll get usefull output if it doesn't match (it's worth a try, 'though).
    Otherwise you'd probably need a "real" parser. They can usually give very accurate positions for the errors (usually off-by-one token/line).

  • Java.lang.Exception: Multiple Matches Found

    Hi,
    I have written scheduler task to connect people soft DataBase get the users list and disable user accounts in IDM . Below is the peace of code.
    =============================
    ResultSet results = stmt.executeQuery(selectQuery);
    tcReconciliationOperationsIntf reconUtil = (tcReconciliationOperationsIntf)getUtility("Thor.API.Operations.tcReconciliationOperationsIntf");
    HashMap[] userValues = null;
    userValues = createDeleteHashMap(results);
    if (userValues.length < 1)
    return;
    Set deletedAcc = reconUtil.provideDeletionDetectionData(this.resourceObject, userValues);
    ============================================================
    In the Set deletedAcc = reconUtil.provideDeletionDetectionData(this.resourceObject, userValues); i am getting the following exception . please help me
    Regarding this.
    [XELLERATE.APIS],Class/Method: tcReconciliationOperationsBean/provideDeletionDetectionData encounter some problems: Multiple Matches Found
    java.lang.Exception: Multiple Matches Found
    Edited by: user11084273 on Sep 26, 2012 12:36 AM

    I believe this API expects only to match no more than one user on each of the criteria set in the paoAccountDataList (userValues) in your case, i.e. each entry in the map must give a unique identifier of one resource. This map is not a map of attributes of one account, which together identify one resource, as any one ambiguous value in the map will give this error. It appears at least one entry in you userValues map is ambiguous and matches multiple resources. I guess this all depends on what your initial select query was.

  • Multiple matches found for CD

    I just started using my iTunes on my MacBook Pro. I began by downloading my new box set of remastered Beatles albums. Some have been no issue. But on others I receive a popup box saying, "Multiple matches found online for this CD. Please choose the correct one." And then it will have 2 or 3 listings of the album title below, some the same, some slightly different- with no way to check to see what you're choosing. On the 1st one I choose the match I thought to be correct and now when I insert that CD all the song names are in Chinese. And no apparent way to change it, the computer recognizes it that way every time now. INFURIATING. Obviously I didn't download it into my iTunes. I even tried other CD's and it happened with some of those, too. I've been using iTunes for a couple of years now and have downloaded dozens of CD's into my library, this is a new issue.
    How do I fix the CD from recognized incorrectly and how do I get this to stop? Thank you.

    If more than one entry is found for the CD (that can occur if more than one person submitted information for the same CD to the Gracenote service), select one of the entries. If it isn’t correct, choose Advanced > Get CD Track Names again and choose the other entry. If it’s still not correct, you can edit the information yourself.

Maybe you are looking for