PowerShell Hashtables

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi my name is nick borson and this is part of a series of videos about learning to program using powershell in this video i'm going to talk about hash tables hash tables are very useful in powershell they're in all kinds of programming languages a hash table is a kind of collection of objects just like an array is a collection of objects but whereas in array the objects are ordered in a sequence and you refer to them by their position by their index in that sequence in a hash table the objects are identified by a name or a key and you refer to the objects by that value so they don't have any particular order instead they have they're associated with some value so it allows you to look up the objects randomly based on some key so for example in in this uh slide here we have we've declared an array and we've declared a hash table so fruits is an array and we've initialized the array by using the at sign with the parentheses or the round braces and then listed the elements of the array and so banana and mango are each elements of that array and if we want to refer to banana we would use it index 0 to refer to banana and index 1 to refer to mango because they're just in that sequence inventory is initialized to a hash table so instead of using the at sign followed by a parenthesis an open parenthesis we use the at sign with a curly brace and it ends with the end curly brace and instead of just specifying uh two values we specify a name here and the equal sign and then a value so we're saying that the name bananas is associated with the value 95 and the name mangoes is associated with the value 21. and then to use the hash table we we can uh you know refer to the name to the to the object and and then we can uh use the square brackets just like we do for arrays this is sort of the the index of operator or the member yeah the the uh the indexing operator but instead of using a a number representing a position in a sequence 0 1 2 3 4 5 and so on we instead refer to the name and then what we get back from that is the object associated with that name or in this case it's the number 95 and i can modify the value or i can store a new value in this case i'm just going to decrement one from that value so hash tables are extremely useful and but enough of slides let's actually get into powershell and try it out so here i am in my terminal window with powershell open and uh let's go ahead and create an array just like just like we talked about i'll go ahead and create an array called fruits and say banana and mango for my fruit array and this is just for review but we can say we can list all the fruits we can then refer to individual fruits by their by their indices so i can say fruits to zero is banana and fruits one is mango i can get the number of fruits by saying fruits.count is 2. so let's now create our hash table so i'll again call it inventory because we're just going to keep track of the number of each fruit we have so i'm going to use the curly brace and i'm just going to put go into new line here instead of putting it all in one line so i'll say bananas we have say 95 and mangoes we don't have quite as many we have 27. okay so if i just type inventory then it gives me this multi-column format so we have the name and one column and the value in another column so for bananas we have 95 and mangoes we have 27. so you have this notion that there's name value these are name value pairs and we refer to each value by it says by its name entering the hash table referred to by its name and that gives us access to its value so if we want to say how many bananas we have do we have we can save fruits and bananas and it will tell us except if i don't mistype it oh sorry inventory that's our hash table inventory bananas and it'll tell us we have 95 bananas and if i want to say i just sold a banana i want to subtract 1 from that i can do i can subtract one and now if i just lift our list the inventory again we'll see that bananas we have now now have 94. so this is very useful because often when um often you want to be able to refer to something for example you have a inventory as an example you want to you want to be able to subtract a banana you don't have to then search your entire array of fruits you just want to go directly to whatever values associated with with bananas okay it might be a part number or you know if it's uh instead of a name it might be a part number or or a uh if it's a collection of people or users it might be um you know some sort of user id or account name or email address or something like that anytime you want to refer to something by a value instead of by its position in a sequence then a hash table is very useful part of the idea of a hash table is that you're going directly to the value you're interested in you you tend to use an array if you just want to store a sequence of values and maybe process them in sequence you want to do something for each for each fruit you want to do the same thing while storing them an array is a very efficient way to just be able to go through all the fruits and do the same thing to each fruit but if you want to keep track of some sort of data for for a whole bunch of different items and then you want to be able to randomly access an item by its name or by some id then that's what a hash table is for so it might be useful then to consider a hash table with a little bit bigger data set so let's go find some data that we can use so here i've done a web search for u.s census population by state and one of the first links here is a page on census.gov so us government census data and if i look at this page then it has a bunch of a bunch of tables that are a matter of public record i can scroll down here and there's a data set data sets section and here there's a little document that describes the layout of this file and here is a data file that says csv format so it's csv format is like a spreadsheet but it's just a simple text file with columns for each with with column separated commas so we can download this file and use that to to give us some data to play with so i'm just going to copy the link here and i'll switch back to my powershell window and here i'll just i'll just assign the url to a variable and there's the url that we want to download now there's a handy powershell command that allows us to just download this url right from powershell so i'll just and that command returns an http http response http is the hypertext transfer protocol when you when you invoke a request you get back a response and uh so i'm going to assign the response to a variable and i'll invoke the command invoke web request and i'll just specify the url and now it's just downloaded that that file from from the internet and if i look at response now then response has a status code it's a 200 http 200 status code means okay we see that the content is here the this is the beginning of the content the content is just one big string um the response also includes headers so uh so the response object actually includes the headers in a in a format that you can use so i can say response dot headers and it gives us all this information that you normally don't you normally don't see when you look at a web page but but every time you send a request to a web server you get back headers followed by the actual content anyway the content is what we're interested in that's the that's the csv data so we can take that just to see what it looks like and well first of all get type it's just a string it's a giant string and [Music] to see what it looks like let's let's just take that and and redirect it to a file i'll just call it census i'll just call it pop for population.csv and if i open that in visual studio code then we can see that the first line has just the column headers and um separated by commas and then each subsequent line is run as one record with the columns separated by commas okay so it's a very simple format and to work with that in powershell we don't really need the csv file anymore i just saved it to a file that notice the right angle bracket is one way to to redirect the output of a command to a file but i can let's delete pop.csv we don't need that anymore but i could take that content and um and convert it from the csv format into a format that is more easy for us to use in our script so i'll just i'll assign the result to that to a variable called csv and i'll say csv equals response response content content and then i'm going to pipe that to the convert from csv command lit okay so now we have this csv object what is that well let's get this type and see what it is okay it's an array of objects so let's look at csv so if it's an array then we can refer to an element by index so there's item object zero so each column each of the column headers has become a property of this object and the associated value is is uh is the value of that property so there was a state column for example well the the uh the value is is here and uh there's a name calling and and the value for this particular record is united states so this and so on so um okay but that's an array and also we can say csv zero get type name so that object is a ps custom object so it's powershell has actually created a an object on the fly that has all these properties where one property each property corresponds to a column head to one of the column headers in the csv file okay so we have an array but we want to put this in a hash table so let's say we want to create a hash table that just has the populations well the again if we look at csv 0 csv 0 let's just let's just use the the census 2010 pop and we want that we have the name and we have the census 2010 pop those are the two that's the name we want as our key and the census 2000 pop is the value we want to associate with that name okay so we'll create a hash table and we're just going to we can initialize previously we created a hash table and initialized it all in one go we can also create an empty hash table so i'm going to call this just pop i'm going to use the at curly brace syntax but i'm not going to put anything in it i'm just going to create a hash table without anything in it and then we'll loop over our array remember csv is an array and for each object in that array we'll execute this code block okay so we will um so we have our pop hash table we're going to assign a value to we're going to add a add an element to the hash table by by by using this array subscript operator here and we're going to use the name of this particular record as our as the key if you will for the value that we're going to assign and then we'll assign to that a key to that name we'll assign the census what was it again pop okay i have to find what that field was called again what that property was called again it was census 2000 okay that's what we're going to assign since this 2000 pop okay so now we've created our we've created our empty hash table and then we looped over all the objects in the um in this csv array and for each of those for each each of those objects we took the census 2000 pop property of that object remember inside the inside the loop the for each object loop here the dollar sign underscore is the pipeline variable it's the current element of the array that we're operating on so we're taking the census 2010 pop property of that object and then we're going to here on the left side of the equal sign this whole expression is referring to an element of the hat of the hash table because we're using this the square brackets to refer to an element of the hash table here here's the hash table the dollar sign pop is the hash table and then the square brackets will then refer by name to an element in a hash table and since that doesn't already exist it means we're going to be creating an element and assigning it this value okay so now we should be able to say dollar sign pop texas and see what the population of texas in 2010 was or dollar sign of hop new york to see what the population of new york was in 2010 okay so that's the basic idea of how you can use a hash table the in the example so far the the keys have all been strings it doesn't have to be a string it can be something else it just has to be something that can be hashed so that generally those are just simple values like strings or numbers and things like that but it can be other types as long as they can be hashed and i won't go into it exactly what that means but uh generally strings things like strings and numbers things that have values um are are are good candidates for being the the key in a in a hash table now what if we um the other thing is that the things we store in the hash table here we've been storing numbers but it can be other things too we can actually um instead of storing just this this single population value we can store the whole object this whole object that that contains all these properties in it let's start over again let's create our let's assign our um our pop hash table to make it empty again and by the way a hash table has a count property so now we can see pop count is zero so there there's nothing in it and let's do it let's do our loop again csv for each object and we'll say pop and again we're going to add an entry based on the name of this record the name property of this current record but instead of just assigning the census 2010 pop value that integer value we're going to assign the entire record as that as that hash table entry okay so we'll do that now if we say pop um texas then we get all the we get an object back that has all these properties for texas so we have the status the the name is texas and we have all these other different pieces of data associated with texas although maybe maybe we don't want all this data maybe we just want the the census 2010 pop and population and maybe the number of births and the number of deaths or let's just say the number of births just to keep it simple well oh by the way now if we say pop count we should say that there are 57 records there are 50 for the 50 states plus there's one for each region plus there's puerto rico it's a territory not a state but it's still there in the census data and there's one for the united states as a whole so there's more than 50. um uh anyway where was i oh yes so um another way that that hash tables are often used is um is people can you can use a hash table as just a way of of grouping values and sort of like creating an object instead of creating an object with properties you can actually use hash table entries and refer to them as a very convenient way in powershell to to almost read them like objects so for example um and part of the reason that's possible is that you can instead of using the the left square bracket syntax like we did here with pop texas okay we can do that but we can also say pop dot texas without the square brackets just use the dot syntax and that actually works now i actually prefer with a hash table to use this syntax because it's more clear that this is referring to an element of hash table but sometimes if you actually want to just create an object that that that contains some values that you want to refer to by name and you want it to just you're not really thinking of it as a as a collection of data for data records you're thinking it is just a an easy way to create an object you can do a use a hash table for that so maybe i want to say here i'll just say texas equals texas okay so now i want to let's say i want to create an object from from texas here that just has the um the population and the number of births well i can say um i'll just call it t equals i can create this thing like so and i'll say population equals texas dot like so and i'll say earth's equals okay first 2010 okay and now i can say t dot population and t dot burst and i could kind of this is just a convenient way of treating this almost like a not like a like this is like i created a class but i haven't actually created class i've just created a hash table but it's a shorthand way of of acting like this as a class and i can refer to this as having properties powershell treating the the um allowing you to use the property syntax versus this syntax interchangeably kind of allows this usage where we can treat a hash table almost like a simple way of creating an object or you know an object with custom properties okay let's combine those two notions we can create a a let's say i want to create a i'll clear my population my population variable again create a empty hash table and this time i'm going to loop over all the csv entries again and then for each object i'm going to create a uh add an element to the hash table once again so pop and again the the we're going to use the the name as the the name of the of the the name property of the record to say the name of the hashtable entry but now for the value of this thing let's just create a little mini hash table that just has these two fields population equals and earth hopefully hopefully i type all that right okay so for each record in the csv dollar stone underscore then became that record so we we assigned to the um we created a uh an entry with that records name property in our hash table and we assign to it a little hash table that just has two members two one of them called population one called births and those are the and the values of those are the or the properties from the uh from that object in the csv okay so now if we say say t equals well let's say let's do new york right we'll do ny equals um sign pop and we'll say new york and if we look at ny then it just has these two records these two properties if you will these two entries population and births so we can say dot ny dot population ny diverse births if i can type and likewise if i want to say pop wyoming dot population then i can do that so it shows you the flexibility of hash tables that create a hash table which in which the values are themselves hash tables or the values can be any other object and the names associated with those values are whatever makes sense for being able to look up data on the fly so this is this allows me to be able to look up the population of wyoming without having to go scan through all the other elements of the hash table to find which record is the one for wyoming so anytime you want to be able to do this kind of associative lookup instead of a lookup by index i'll look up by a certain things pieces of data associated with some value that's what a hash table is for that's actually a term that is sometimes used for to distinguish between things like arrays that are ordered or sequential containers or collections versus things like hash tables that are associative collections so instead of storing things based on their sequence they store things by associating them with some sort of name or key that you can then use to look them up all right i think that's a enough to give the basics of how powershell hash tables work and they're extremely useful so i hope that you will enjoy using them thanks
Info
Channel: Niklas Borson
Views: 3,167
Rating: undefined out of 5
Keywords:
Id: Ply9g3aVOK8
Channel Id: undefined
Length: 25min 18sec (1518 seconds)
Published: Sat Apr 10 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.