Learn PowerShell: Episode 4, Types + Methods + Casting

Jun 22, 2021 00:12 · 5065 words · 24 minute read

Hello everyone, and welcome to the fourth episode of the PowerShell video series.

00:04 - We are ploughing through PowerShell and hopefully it’s all making sense.

00:08 - In the last video we talked about reading from CSV files.

00:12 - And just before we dive into the topic for this video, let’s quickly go over what exactly we did.

00:17 - We had a CSV file of students here, and we wanted to add a new “Sum” column to it here, with the sum of the “Maths” and “English” score of each student.

00:27 - So, we used “Import-Csv” to read in the data in the CSV and file, and we put that into a variable called “students”.

00:36 - Then in order to be able to actually add the “Maths” and “English” from here, we converted them into numbers.

00:42 - So we take our “students” and use a “ForEach” to go through each item and set that item’s Maths score to the Maths score but as an int (whole number).

00:56 - And we repeat that with English. And now that the “Maths” and “English” are definitely numbers, we can add a new “Sum” property to each student and put the correct thing into it.

01:07 - So yet again, we’ll go through the “students”, and we’ll go through each one and then we’ll use “Add-Member” to add a new member, a new smaller part to the object.

01:18 - And the InputObject on that will be the current item like so, with the member type being “NoteProperty”, the “Name” being “Sum” and for the value we want it to be the “Maths” plus the “English”.

01:33 - And if you’ll recall from the last episode, this bit here needs to be in brackets so it’s very clear we want it to do this + here against these two and then use the result from that here.

01:47 - Which is different from without where we’re basically saying run the command and then add the “English” score, which makes no sense.

01:58 - And that’s what we did last video but… As I mentioned right at the very end of the last video… This is really long.

02:06 - Is there a way we can shorten this? Well, yeah! There are ways we can shorten this down.

02:11 - And I’m going to show you a few tricks we can use to make this a lot easier to write right now.

02:24 - The very first thing is an absolute lifesaver.

02:28 - One of the biggest problems we have here is we keep writing this “ForEach” here over and over again, and honestly, it’s getting quite repetitive.

02:39 - However, there is actually an alias for “ForEach”, called percent.

02:45 - So instead of writing “ForEach” all the time, we can actually just write “%”. And already that helps us out a lot.

02:53 - It’s much easier, and I’ll be using this from now on in the series.

02:57 - Another problem is how long this “Add-Member” is.

03:00 - I mean, look at all of this. But, yet again, the PowerShell developers have thought of this, they’re more than aware, and have given us a few very nice shortcuts on this command.

03:11 - Firstly, instead of having to write “-InputObject” and all of this, we can actually just pipe our object in.

03:18 - So, we’ll just do “$_ |” into “Add-Member”.

03:24 - That trims a lot of fat already. Is there anything else we can do? Well, you see, when “Add-Member” was first introduced, once thing t started to become very clear: Above 95% of the time people were using it, they were using add a NoteProperty.

03:40 - People don’t want any of the “ScriptProperty”s or “CodeProperty”s, they almost always use this command to add NoteProperties.

03:49 - And that is why they added a parameter called “-NotePropertyMembers”.

03:55 - And this parameter is fantastic. The way we use this parameter is instead of writing the “MemberType”, instead of writing the “Name” and instead of writing the “Value”, we simply write “-NotePropertyMembers” and then we write this.

04:12 - Now, I’ll explain what exactly this syntax is later on in the series, but for now just stick with it.

04:18 - We’re going to write an at sign, followed by curly braces.

04:23 - And inside these curly braces, what we do is we write “Sum = ” the Maths plus the English.

04:33 - And that’s it. I mean, you can’t get shorter than this.

04:36 - We’re adding some “NoteProperty” members and it’s called “Sum” and we’re setting it to the maths and English.

04:42 - And what’s great is you can even add more than one note property with this, as you’ll see when we learn about this “@” thing later on.

04:51 - And just by applying these our commands can made considerably shorter.

04:57 - From now I’ll definitely be using the “%” alias.

05:00 - Now then, as hopefully you’ve learnt by now, “objects” are perhaps the most central part of PowerShell, everything is built around them, and as a result, there is a fair amount to them, they’re literally the thing that makes PowerShell work, so of course there’s quite a bit of stuff there.

05:17 - And because of this, in this video I think it’s time we dig deeper into objects.

05:22 - Now, I want to introduce something to you called types.

05:26 - When we have an object, that object always has a type attached to it.

05:32 - A type is essentially a description of what properties or, what members an object must have.

05:39 - For example, when I run “Get-Process”, this gives us a bunch of objects, and every single object it gives back are “ProcessInfo” type of objects.

05:49 - Meaning all those objects have the exact same properties on them, all the properties to represent processes.

05:58 - Almost every type we use is from these bits of the system.

06:02 - So, the “ProcessInfo” type would come from the “. NET library”, and the “CommandInfo” type would come from PowerShell’s core.

06:09 - And every type is basically a definition of the members, of the smaller parts, a certain object has.

06:18 - So, to sum it up, the type is essentially of what kind of object we have, and therefore what properties and members that object must have on it.

06:29 - And to be clear, I’m talking about regular properties, NoteProperties are just added to any object whenever you feel like it.

06:41 - Alright so, that’s what types are, every object follows some type.

06:47 - And in PowerShell, if we ever for some reason want to represent a type, as in actually refer to the literal type, what we do is we write square brackets and put the type in there.

06:59 - So, let’s say I wanted to reference the “string” type, which is the type on text objects, I’d just write square brackets and then put “string” in there.

07:08 - And there you go; it’s given me an object that tells me all about the “string” type.

07:13 - Now, hopefully you recognise this square bracket syntax from the last episode.

07:18 - How do we convert from a string into a number? Well, if I put “123” into the variable “s”.

07:27 - To convert it, get “s” and do square brackets “int” before it.

07:33 - Where “int” is the type used to represent whole numbers.

07:36 - So, this new knowledge about types actually explains a little bit what this is.

07:41 - We’re taking what’s in “s” and then we’re saying we want to treat it like it’s the type “int”, which means it will convert from the string type that it was into an int (number) type.

07:53 - And in the programming world this has a bit of fancy word to it, this is called casting.

07:58 - The idea of converting one kind of object into another.

08:01 - Don’t ask me why we called it that, but that’s what it’s called.

08:05 - Now, of course, we can’t cast everything. I couldn’t just decide that I want to cast a single little integer into an entire “FileInfo” object.

08:17 - That just doesn’t make sense, how on earth is it supposed to make a file object out of just one integer? So, you can’t cast absolutely anything to anything, but that’s casting, turning an object from one type to another.

08:31 - Alright cool, so that’s what’s going on with objects.

08:34 - Every single object has a certain type, and we can get information about that type by writing square brackets and putting the type’s name inside them.

08:45 - And you can also use this similar syntax for casting, simply put the type in square brackets before something and that will cast it from what it was into the new type you put there.

08:56 - Now let’s look at properties a little closer.

08:59 - Now, note properties are very straightforward, you can make them whenever you want, and you put absolutely whatever type of object you want into them too.

09:08 - That’s all there is to those. However, the regular, built into the code, properties are slightly different.

09:16 - Every normal property has two things. They have a name, which is what the property is called, and they also have a type.

09:26 - And this type is what type of object the property will have in it.

09:31 - For example, let’s say I have a “ProcessInfo” object, and one of the things it stores is the name of the process.

09:41 - So, it has a “Name” property. And on that property, the type would be a string, the type for a text object.

09:48 - So, what that means is the property will ever have a string in it.

09:54 - It must have text in it. So, with note properties, you can just put whatever type of object you want into it whenever you want, but with regular properties, they have restrictions allowing only specific types of objects in.

10:09 - This is actually a really good thing because it stops you from potentially doing stupid stuff like putting a number object into the name property of a file, and it means that all of the code that works with the file objects knows that there will always be a string in that property, no problems.

10:31 - Alright, so that’s all good, we have different types of objects for different things, and each different type of object is made up of different members.

10:39 - “Members” meaning all the smaller stuff in the object.

10:42 - We know two kinds of members you can get so far; we know about regular properties and the neat little note properties.

10:49 - However, as you know, these aren’t the only members, there’s “ScriptProperty”s and “CodeProperty”s and all this other stuff that doesn’t really matter too much, but there’s one more kind of member that we need to know about.

11:01 - So far, we’ve looked at the two kinds of properties you need to know about, and as you know, properties are the way we store data on an object, it’s… Broken down into properties.

11:12 - However, you see, objects don’t just have to have data on them, objects can also have code inside them, they can “do” certain actions.

11:24 - And all of that code inside them is organised into things called “methods”, a. k. a functions.

11:32 - Think of a method like a command, except you can perform that command actually to a specific object.

11:39 - A method is essentially a block of code that does some action, and we can run it.

11:44 - I think it’s best if I show you an example.

11:46 - So, let’s say we had a FileInfo object that represents a file, and in it we’ll have all of our properties as usual, but we’ll also have some methods, some actions we can take on the files.

11:59 - For example, “Delete”ing the file could be a method.

12:04 - When we run this method on one of our file objects, it will delete the file that object represents.

12:11 - Another example, what if we have an object that represents a process? What methods do you think we could put on there? Well, how about a Kill method.

12:23 - We run this method on a certain process object, and it will kill the process that object describes.

12:30 - Alright, so a method allows us to perform some action on a certain object.

12:35 - And just like properties, methods are shared across types.

12:40 - So, every process object will always have the exact same methods and properties available, every file object will always have the exact same methods and properties available, and so on.

12:51 - And, just like commands, methods can also have parameters on them.

12:59 - And remember how properties are limited to only contain a specific type of object? Well, in a similar way, the parameters on methods are too! Say I have a “Rename” method that takes in a new name parameter.

13:14 - That new name parameter would be set to only accept strings.

13:27 - Commands are actually the same way too, each of their parameters only accept certain types of objects.

13:37 - But the thing is, and the reason you often don’t notice that all things are limited to only specific types is PowerShell actually does a really good job of automatically converting the objects you try to put them into these parameters.

13:53 - So, as an example, I was talking about the “Rename” method taking in a string parameter earlier.

13:59 - If we were to let’s say try to put a file object into that parameter, so I tried to take some variable with a file object in it and use that as what to put in the parameters, PowerShell would automatically try to cast the file object into a string so it works.

14:19 - And what would that give us? If it tries to automatically cast my file object into a string (so it fits into the parameter), what string do I get out of that? What does casting from FileInfo to string give us? Well, let’s find out.

14:38 - So, I’m going to get all the files in this folder and I’m just to take just one of them, let’s say this one, we’ll get just that one using “Where”.

14:47 - So, where the name is exactly that. And there we are, there’s that one object.

14:54 - And we’ll put that one file object into a variable called “file”.

14:58 - And now, we’re going to try and convert this file object here into a string, just like this.

15:06 - And let’s see what doing that gives us back.

15:09 - And there we are, so when you convert from a file object to a string, the string it gives back basically contains the path to that file, which makes sense.

15:21 - In fact, this is actually what you want it to turn into most of the time.

15:24 - For example, if we use “Get-Help” to find out about “Import-Csv” for a second, we can actually see if we look here that the Path parameter wants a string.

15:37 - This parameter on the command takes in only strings.

15:41 - Now, let’s say I do “Import-Csv” and for the path parameter, I don’t give it text, I give it my file object here.

15:54 - If we do that, you’ll notice… It works perfectly.

15:58 - No error or anything. And the reason why is because PowerShell has automatically casted this file object into a string, because it’s seen “Oh hey, this parameter here wants a string, but we’re trying to give it a file object, so let’s just try and turn file object into a string, so it goes into that parameter”.

16:21 - And when it did that conversion, the string it turned into was just a path to the file, which is… Exactly what it wanted so, that’s fine.

16:30 - So, PowerShell is really good at casting between types automatically, because it wants this stuff to get as little in your way as possible.

16:38 - However, even though PowerShell will work hard to do these things automatically and make them just work, it’s still useful to actually understand what’s really going on here, which is that a lot of these things are limited to only a specific type and what happens is if you try put in something that doesn’t match the same type, PowerShell will just try to turn it into that type of object for you.

17:06 - So, methods take in things through their parameters.

17:09 - And they can also give back things, known as “returning” things.

17:14 - Returning things back to us. And yet again, just like the parameters, every method will return a specific type of object.

17:24 - So, we may get a “string” back, or an integer back, it all depends on the method.

17:29 - Not every method will return something back to you, but it can.

17:33 - Again, just like with commands. Commands can, and usually do, give back objects, but not all commands have to give back objects, some might just do something and that’s all.

17:46 - Alright so I think that’s enough of me going on about all this theory, how about we go back into PowerShell and actually use some of this.

17:54 - So, how about we actually run one of these methods.

17:58 - Now, I’m going to introduce you to a method called “GetType”.

18:03 - This particular method is interesting because every single type of object in existence has this method.

18:10 - So, no matter what object you have and what type it is, it will always have a ‘GetType’ method on it.

18:19 - And what this method does is it tells us about what type an object is.

18:25 - So, if I had a string object and I ran “GetType” on it, it would give me information about the “string” type.

18:33 - This method has no parameters, so it doesn’t take in anything, but it does give back a “Type” object.

18:43 - Which is a type of object you can get that tells you… About a type.

18:47 - This is actually the same object you get when you write a type’s name in square brackets.

18:53 - If you remember from earlier, if you want to find out details about a type with a certain name, you write square brackets and put the type inside them (on its own of course, if you put something immediately after it then that would be casting).

19:03 - Anyway, when you do that, when you write a type in square brackets without anything after it, what this does is it gives you a “Type” object telling you about the type you entered in the square brackets.

19:18 - So, both of these two things give you a “Type” type of object telling you about a type.

19:24 - A lot of “type” in that sentence I know. So, “GetType” gets us the type of an object, and the square brackets gets information about the type with the name you put in.

19:27 - So, if I have an object in variable “o” and I don’t know what type it is, I can just run “GetType” on it and find out, “GetType” will tell me exactly what type it is! Let me show you.

19:39 - So, here we are within PowerShell, and I’m going to make a new variable called “s” and I’m going to put a string inside it.

19:47 - The way we make a string is simply by writing quotes and putting whatever text we want inside.

19:52 - So, let’s say “abc”. There we are, my variable “s” now has the string, the text, “abc” in it.

20:02 - Now, let’s first see what we get when we write “square brackets” with string in the middle.

20:07 - So, if I hit ENTER, here you’ll see we get information about the type called “string”.

20:12 - However, what if I have a variable like “s” and I don’t know what type it is has in it, and we want to find out? What can I do then? Well, then we can run the GetType method on our object, which will give back info about whatever type of object it is.

20:28 - So, let’s do that. Now running methods is really similar to getting properties.

20:34 - We take our variable with the object we want to run the method on, then do a dot, and then write “GetType”.

20:40 - However, there is just one thing we need at the end here to tell PowerShell that we want to run a method and not get a property.

20:49 - And that one thing is brackets, like so. These brackets at the end make it clear to PowerShell and to us too that we are running a method, as opposed to getting a property.

21:04 - So, I’ll do that and since “s” contained a “string” type of object, “GetType” is going to give back all the details about the string type.

21:16 - So, this makes “GetType” an excellent way to find out what type an object is.

21:21 - Let’s say that here in this variable called “file” I have one single file object.

21:27 - Now, what I want to know is: What actually is the type for a file object called? What’s the actual name of the “file object type”? Well, all we have to do is run “GetType” on this object and it will return back info about what type it is.

21:42 - So, we’ll take our “file” object and run the “GetType” method on it.

21:46 - Ah, here we are, here’s some information about the type, and if we look at the “Name” here we’ll see it’s called “FileInfo”.

21:53 - Cool, so that’s what the type for file objects is.

21:56 - So, there we are, we just ran our first method.

21:59 - Well, this is the first method we ran ourselves at least, inside PowerShell there are thousands being run.

22:06 - One thing I just want to say before we move on, I’ve been saying “We’re going run this method” or “We ran this method”, but there’s actually a more specific word than that.

22:19 - For whatever reason, in the programming world when we describe running a method, what we actually say is ‘calling’.

22:27 - So, when you call a method, it means you’re running that method.

22:32 - I don’t know why in the programming world we call it that, but that’s just what it’s called.

22:38 - I’m… not sorry. So, let’s get all the processes on the system.

22:44 - And for each one of them, we’re going to call the GetType method.

22:47 - So, for each one we take current object we’re on and call GetType.

22:54 - And just like getting properties, just like running commands, just like all of those, ForEach will take what the method returns each time, and it will collect it all together.

23:05 - So, if we have 10 process objects, it’s going call “GetType” 10 times and bring all the results from those together, and we’ll get 10 type objects back.

23:17 - Let’s run it. And here we are. So, it went through each object and called “GetType” on each of them, and this is the result from each one.

23:26 - So yeah, no surprise here, every single object was a “Process”, ‘cause that’s not exactly going to change, they’re all process objects.

23:32 - Now let’s just take a quick look one of these type objects on their own.

23:37 - So, as we know there are a few ways we can get them.

23:39 - We can go the square brackets way like this, or we can take something, like let’s say a string, so a string with “abc” inside it, and then take that object and do dot “GetType”.

23:50 - So, we’re taking our string from here and running “GetType” on it.

23:56 - And here’s the “Type” object. A lot of these properties don’t really matter, right? The property we’re really interested in is the “Name” property here.

24:04 - This is what the type is called. However, there are more properties actually, the table just isn’t showing them, so we’ll take the type object from here and we’ll pipe it into “Format-List” so we get a more complete list.

24:17 - And… Yeah, there are a lot of properties on there.

24:20 - It has basically everything you could ever want to know about a type.

24:24 - Like, for example, the “FullName” property near the top here.

24:28 - You see, this “Name” property here is actually a shortened version of this.

24:32 - So, we can see that the type is really called “System. String”, that’s the full, proper name for this type.

24:39 - But honestly though, I’m not really going to look through this, ok? You’re free to explore these as you want and take a look at what they have inside them, there’s loads of stuff, a lot of it probably won’t even make sense right now, but some of it is some very, very complex things that you just… just don’t need to worry about.

24:54 - One thing that’s quite is these type objects have a method called “GetProperties”, which will give us a list of all the properties in that type.

25:04 - So, here I have a file object, and if I take this object and get the type of it, we’ll see it’s a “FileInfo”.

25:12 - And then, what I’m going to do is I’m going to take this type, take the object this “GetType” gave us, and I’m going to call the method “GetProperties” on it.

25:23 - So, to break this apart, we take our object in our variable, then we call “GetType” on it, and that will give us back a “Type” object.

25:32 - And we then take that “Type” object it gave back, and we reach into that and run the “GetProperties” method.

25:37 - And let’s just take this further and let’s take these properties and pipe them into “Format-Table”, just so it shows them as a table.

25:47 - And here we are, here’s a list of all the properties in the “FileInfo” type.

25:52 - So every “FileInfo” type must have these properties in it.

25:57 - So we see there’s a “Name”, there’s an “Extension”, there’s a “LastAccessTime”, “LastWriteTime” and you can actually even if you go over here, you can actually see what types these properties are, what type of objects they contain.

26:12 - So the “Name” is a “string”, the “Extension” is a “string”, the “LastWriteTime” is a “DateTime” because it’s a date and a time.

26:20 - Uh, so you can just sort of see the types that these things are.

26:23 - And I think that’s enough on methods and types for this video.

26:26 - But just before we close off the video, I want to talk about the difference between commands and methods.

26:33 - Let’s say you have a file object, and you want to delete the file that object refers to.

26:39 - There are two ways you can do it: You can either pipe your object into the command “Remove-Item”, which will, delete the file.

26:46 - Or you can also take the file object and call “Delete” on it.

26:51 - Well, which one should you do, and why are there two ways to do this? Well, the answer to the first question of which one you should do, is: Use the command.

27:01 - If there’s a command available to do what you want, just use that command.

27:06 - It’s there, it’s been built specifically for PowerShell so it’s just going to be the easiest, best way.

27:13 - In fact, inside the command, it probably just goes and runs the method anyway, that’s what the command does for you.

27:19 - So, if there’s a command to do what you want, just use the command.

27:24 - However, there are… A lot of things in the world.

27:29 - And the thing is you can’t have a dedicated PowerShell command for every single thing out there you could be doing.

27:36 - When you start to do more advanced things in PowerShell, sometimes you may not have a command to do it for you, and you need to go just a little deeper and start using the actual methods on the objects provided by. NET, as opposed to using the nicer commands which basically sit on top of those methods.

27:57 - So hopefully that slightly clears up why we have both commands and methods.

28:02 - Quite simply, the command is the thing designed specifically for PowerShell, it’s made to be used in PowerShell, but if you start doing those more advanced things you may need to use the methods instead.

28:16 - So that’s all, so thank you for watching this video, the next video is basically part 2 of this video.

28:21 - We’re going to take an even closer at methods, we’re going to take an even closer at objects, a closer look at types, we’re just going to take a closer look at everything we looked at here.

28:30 - (Man, you know, literally half the video was improvised, I don’t know why, I just… Improvised) (and I had to specially subtitle the bits that deviated from the script!).