none
[Powershell] Find missing number in a array RRS feed

  • Question

  • Hi all,

    Is it possible to find a missing number in a array?

    For example:

    I have read a file using the Get-Content cmdlet which places all lines in an array.

    The CSV has only numbers: 001,002,003,004,006

    What I would like to do is store the missing number: 005 in a variable (and then exit, even if there are multiple missing numbers) if there are no missing numbers then store 007 in a variable.

    Is this possible?

    Thanks in advance!

    Regards,

    Bart


    Bart Timmermans | Consultant at inovativ
    Follow me @ My Blog | Linkedin | Twitter

    Please mark as Answer, if my post answers your Question. Vote as Helpful, if it is helpful to you.



    Wednesday, April 17, 2013 9:05 PM

Answers

  • Think about things like calculating the next prime number --- or --- the next number in a Fibonacci sequence.

    What is the next number after "infinity"?


    ¯\_(ツ)_/¯

    Wednesday, April 17, 2013 9:29 PM
  • Active Directory searches aren't sorted unless you specifically request it. One solution is to request an order when you query AD. Another is to sort after you retrieve your results. Either way, why does it matter?

    Bill

    Monday, April 22, 2013 6:54 PM
    Moderator

All replies

  • Absolutely possible.  It is a great exercise for learning how to write a PowerShell script.  Give it a try and ask specific questions about the problems you are having.

    I suggest that you start by sorting the array.

    Remember that actually doing this will tell you more about how a script works than all of the questions you can invent.


    ¯\_(ツ)_/¯

    Wednesday, April 17, 2013 9:26 PM
  • Think about things like calculating the next prime number --- or --- the next number in a Fibonacci sequence.

    What is the next number after "infinity"?


    ¯\_(ツ)_/¯

    Wednesday, April 17, 2013 9:29 PM
  • What is the next number after "infinity"?

    I believe it's 42. ;-)
    Thursday, April 18, 2013 9:45 AM
  • Just a thought: if you get-content on a file purely containing: "001,002,003,004,006", you'll get a text string, not an array. You can, of course, split this down into an array, but you'd have to write some code to do that.

    You could use import-csv to import from a file, as an array. This might give you more immediately flexibility, but the same information in a file would need to be structured differently - delimited by carriage returns (for 'rows') rather than commas (which mean 'columns'). The CSV file would also need a header row, or you'd have to specify one to the cmdlet when you import.

    Thursday, April 18, 2013 9:53 AM
  • Hi All,

    Thank you for all your replies and not making it to easy for me :). I have created the following script:

    $objDomain = New-Object System.DirectoryServices.DirectoryEntry
    
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
     $objSearcher.SearchRoot = $objDomain
     $objSearcher.Filter = "(&(objectCategory=Computer)(cn=DWSSC*))"
    
    $colProplist = "name"
     foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
    
    $colresults = $objSearcher.FindAll()
    
    $current  = 0
    $previous = 0
    $new_name = $null
    
    foreach ($objResult in $colResults)
         {
     $objComputer = $objResult.Properties
     $objComputer.name
        $cn = "" + $objComputer.name
        $current = [int]$cn.Substring(6)
     
        # Check for avialable computername
        if( $current.CompareTo($previous+1).Equals( 1 ) )
        {
            $new_name = $previous+1
            break # no need to search anymore
        }
     
        $previous = $current
    }
     
    # If no available computername use next in line
    if( !$new_name )
    {
        $new_name = $current+1
    }
     
    # Prefix number with 0's if needed
    if( $new_name.CompareTo(10).Equals(-1) )
    {
        $new_name = "00" + $new_name
    }
    elseif( $new_name.CompareTo(100).Equals(-1) )
    {
        $new_name = "0" + $new_name
    }
     
    # Prefix name with constant
    $new_name = "DWSSC" + $new_name
    $new_name

    What it does...connecting to Active Directory and find all computers starting with DWSSC. Then it starts comparing and adding numbers till there is a good result. I did work last weekend. But now it stopped working. The results are not sorted the right way. When I run the below part of this script:

    $objDomain = New-Object System.DirectoryServices.DirectoryEntry
    
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
     $objSearcher.SearchRoot = $objDomain
     $objSearcher.Filter = "(&(objectCategory=Computer)(cn=DWSSC*))"
    
    $colProplist = "name"
     foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
    
    $colresults = $objSearcher.FindAll()
    
    $current  = 0
    $previous = 0
    $new_name = $null
    
    foreach ($objResult in $colResults)
         {
          
     $objComputer = $objResult.Properties
     $objComputer.name
        $cn = "" + $objComputer.name
        $current = [int]$cn.Substring(6)
        }

    The output is:

    DWSSC001

    DWSSC002

    DWSSC004

    DWSSC003

    DWSSC005

    DWSSC006

    DWSSC007

    DWSSC008

    When I run the complete script it returns DWSSC003 as $new_name will it should be DWSSC009. It is ok to fill in the gaps like it does now...but only with correctly sorted data.

    Does anyone have a solution for me?

    Kind regards,

    Bart Timmermans


    Bart Timmermans | Consultant at inovativ
    Follow me @ My Blog | Linkedin | Twitter

    Please mark as Answer, if my post answers your Question. Vote as Helpful, if it is helpful to you.


    Monday, April 22, 2013 6:33 PM
  • Active Directory searches aren't sorted unless you specifically request it. One solution is to request an order when you query AD. Another is to sort after you retrieve your results. Either way, why does it matter?

    Bill

    Monday, April 22, 2013 6:54 PM
    Moderator
  • $colresults = $objSearcher.FindAll() | Sort-Object @{Expression={$_.Properties.name}}

    It is now fixed. I added the Sort-Object after the $colresults.

    Maybe there are easier methods for finding "free" computer names. But for now this is working.

    Thanks all!

    Regards,

    Bart


    Bart Timmermans | Consultant at inovativ
    Follow me @ My Blog | Linkedin | Twitter

    Please mark as Answer, if my post answers your Question. Vote as Helpful, if it is helpful to you.

    Monday, April 22, 2013 7:18 PM
  • What is the next number after "infinity"?

    I believe it's 42. ;-)

    no, the next number after "infinity" is actually "and beyond", or so says Buzz Lightyear.

    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    Monday, April 22, 2013 7:22 PM
  • What is the next number after "infinity"?

    I believe it's 42. ;-)

    no, the next number after "infinity" is actually "and beyond", or so says Buzz Lightyear.

    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    I actually didn't think I would get away with that but - ha!  I did.

    'infinity' is NOT a number ... NaN.

    Even mathematicians use infinity like a number such as Dick Feynman and his "problem with infinities" but even Dick admitted the usage was incorrect.  Only number theorists seem to always get it right.

    There is a very good book: "The Man Who Knew Infinity" by Robert Kanigel,  It is worth the read. (on Kindle too).


    ¯\_(ツ)_/¯

    Monday, April 22, 2013 8:55 PM
  • Infinity may not be a number, however that does not mean that no number can be after it. numbers do not need to be ordered, especially when being compared to things that are not numbers. Perhaps that explains why 1 am this morning followed 11 pm last night. And "two" follows "infinity", at least according to the dictionary.

    that said, my suggestion of "and beyond" (another NaN) is no more and no less a number than infinity.

    As an aside I find it ironic that, as you say, only "number theorists" properly appreciate that "infinity is NaN", when you would expect this to be more in the realm of "non-number theorists". Kind of like saying that only carnivores know that tofu is not a meat. Tell that to your vegetarian friends.

    And while we are speaking of semantic absurdities, my first response to the original question "Is it possible to find a missing number in a array?" was going to be "No, you can't find it in the array because it is, by definition, missing. if you could find it there it would not be a missing number".


    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    Thursday, April 25, 2013 4:59 PM
  • Infinity may not be a number, however that does not mean that no number can be after it. numbers do not need to be ordered, especially when being compared to things that are not numbers. Perhaps that explains why 1 am this morning followed 11 pm last night. And "two" follows "infinity", at least according to the dictionary.

    ...

    "Aled_L likes this" ;)

    Friday, April 26, 2013 8:11 AM
  • Infinity may not be a number, however that does not mean that no number can be after it. numbers do not need to be ordered, especially when being compared to things that are not numbers. Perhaps that explains why 1 am this morning followed 11 pm last night. And "two" follows "infinity", at least according to the dictionary.

    ...

    "Aled_L likes this" ;)

    I bet you like the tooth fairy too.  Don't believe every thing you see posted on the Internet.  There is no dictionary that says that two follows infinity.

    There is no infinity.  It I just a straw man.


    ¯\_(ツ)_/¯

    Friday, April 26, 2013 8:16 AM
  • Infinity may not be a number, however that does not mean that no number can be after it. numbers do not need to be ordered, especially when being compared to things that are not numbers. Perhaps that explains why 1 am this morning followed 11 pm last night. And "two" follows "infinity", at least according to the dictionary.

    ...

    "Aled_L likes this" ;)

    I bet you like the tooth fairy too.  Don't believe every thing you see posted on the Internet.  There is no dictionary that says that two follows infinity.

    There is no infinity.  It I just a straw man.


    ¯\_(ツ)_/¯


    PS C:\Users\Al> "two","infinity"|sort-object
    infinity two PS C:\Users\Al>

    I rest my case, assuming that the dictionary uses the same alphabetic sorting order as sort-object does.


    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    Sunday, April 28, 2013 4:24 AM
  • I nominate AL for a Nobel prize in ...what?

    Al and Alice would begood on the same croquet team but the smoky caterpillar would probaly object.


    ¯\_(ツ)_/¯

    Sunday, April 28, 2013 5:13 AM
  • I nominate AL for a Nobel prize in ...what?

    Al and Alice would begood on the same croquet team but the smoky caterpillar would probaly object.


    ¯\_(ツ)_/¯

    the Nobel Prize in politics, of course! He managed to redefine the problem to fit an answer already on hand. :D

    The prior recipient was, I believe, Humpty Dumpty*.

    ----------------------------------------

    "When I use a word," Humpty Dumpty said, in rather a scornful tone, "it means just what I choose it to mean—neither more nor less."



    • Edited by Alex K. Angelopoulos Sunday, April 28, 2013 6:00 AM Wrong fictional Nobel Prize in Politics recipient. Oops.
    Sunday, April 28, 2013 5:37 AM
  • Alex - Ok and what did the Jaberwok say?


    ¯\_(ツ)_/¯

    Sunday, April 28, 2013 5:52 AM
  • One Lewis Carroll quote a night is my limit. ;)
    Sunday, April 28, 2013 6:03 AM
  • There are more things in heaven and earth, Alex, Than are dreamt of in your philosophy.

    or

    Don't sweat the small stuff.

    Have a nice night.


    ¯\_(ツ)_/¯

    Sunday, April 28, 2013 6:07 AM
  • I nominate AL for a Nobel prize in ...what?

    Al and Alice would begood on the same croquet team but the smoky caterpillar would probaly object.


    ¯\_(ツ)_/¯

    the Nobel Prize in politics, of course! He managed to redefine the problem to fit an answer already on hand. :D

    The prior recipient was, I believe, Humpty Dumpty*.

    ----------------------------------------

    "When I use a word," Humpty Dumpty said, in rather a scornful tone, "it means just what I choose it to mean—neither more nor less."




    Nobel accepted, of course. But actually getting it - that is one of the six impossible things I will believe before breakfast tomorrow.

    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    Sunday, April 28, 2013 7:18 PM
  • @Al - just one more thing you don't have to figure out now.  Only five more to go.


    ¯\_(ツ)_/¯

    Sunday, April 28, 2013 8:10 PM
  • First - I appreciate this script and the banter following it.

    Second - I reworked this script a bit. It prompts for a prefix, counts the prefix, and removes that from the number of the machine.

    $SearchComputers = read-host "What is the computer prefix?"
    $PrefixCount = $SearchComputers | Measure-Object -Character | Select-Object -ExpandProperty characters
    
    $Computers = Get-QADComputer *$SearchComputers* | Select-Object Name | Sort-Object Name
    
    foreach ($Computer in $Computers){
    
    $Computer = $Computer.Name
    [int]$CurrentNumber = $Computer.Substring($PrefixCount)
    
    if ($CurrentNumber.CompareTo($PreviousNumber+1).Equals( 1 ) )
        {
          $MissingNumber = $PreviousNumber+1
          Write-host "Missing Computer: $SearchComputers$MissingNumber"
        }
    
     [int]$PreviousNumber = $CurrentNumber
    }


    If my answer helped you, check out my blog: DeployHappiness. Subscribe by RSS or email. 

    Tuesday, July 23, 2013 4:42 PM
  • Is there a way to make this script display multiple results - possibly give you the next 5 available host names? when i run it it only displays 1 result.

    thanks for the help.

    Thursday, October 24, 2013 12:38 PM
  • Is there a way to make this script display multiple results - possibly give you the next 5 available host names? when i run it it only displays 1 result.

    thanks for the help.


    That is correct.  Can you ask a new question.  This one has been closed for some time.

    ¯\_(ツ)_/¯

    Thursday, October 24, 2013 12:42 PM
  • I wrote something similar to get the first available lun from an azure vm

         $Luns = @() 
         try   {$Luns = $VM.StorageProfile.DataDisks.lun}
         catch {$null = $Luns}
         if ($null -ne $Luns)
            {$LunsCount = $VM.StorageProfile.DataDisks.count
             for ($i=0; $i -lt $LunsCount; $i++)
                 {if  ($i -notin $Luns)
                      {$Lun = $i; break}
                  else{$Lun = $i+1}
                 }
            }
         else {$Lun = 0}

    Friday, November 8, 2019 11:08 AM