Script Blocks Decoded
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Title of Series | ||
Number of Parts | 60 | |
Author | ||
License | CC Attribution - ShareAlike 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this | |
Identifiers | 10.5446/37405 (DOI) | |
Publisher | ||
Release Date | ||
Language | ||
Producer | ||
Production Year | 2018 |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
|
1
10
14
18
24
25
26
32
34
40
41
44
46
54
00:00
Scripting languageCodierung <Programmierung>Fundamental theorem of algebraData structureStatement (computer science)Module (mathematics)AerodynamicsModul <Datentyp>Constructor (object-oriented programming)Object (grammar)Function (mathematics)Process (computing)Set (mathematics)Fundamental theorem of algebraSinc functionData structureStatement (computer science)Parameter (computer programming)Process (computing)Scripting languageDependent and independent variablesContent (media)Revision controlComplete metric spaceKey (cryptography)Dynamical systemScheduling (computing)Beta functionModule (mathematics)Functional (mathematics)Heegaard splittingSemiconductor memoryMetaprogrammierungObject (grammar)BitMultiplication signQuicksortRight angleGroup actionSemantics (computer science)Poisson-KlammerComputer animation
05:17
Function (mathematics)Scripting languageStatement (computer science)Codierung <Programmierung>Event horizonScripting languageText editorEmailGroup actionFunctional (mathematics)QuicksortTrailBitStatement (computer science)NumberWindowComputer animation
06:46
Scripting languageCodierung <Programmierung>Graphic designWindowDemo (music)DemonConvex hullLimit (category theory)Scripting languageElectronic mailing listStatement (computer science)2 (number)Computer animation
07:19
Convex hullScripting languageCodierung <Programmierung>Demo (music)WeightFunction (mathematics)Inclusion mapDemonGraphic designInternet forumGame theoryFunctional (mathematics)Plasma displayFile formatEmailExecution unitAugmented realityFluidDynamic random-access memoryProgrammable read-only memoryDefault (computer science)Parameter (computer programming)Host Identity ProtocolPower (physics)Maxima and minimaMoment of inertiaOperator (mathematics)Scripting languageElectronic mailing listSystem callDifferent (Kate Ryan album)Functional (mathematics)Mixed realityExpressionMatching (graph theory)Line (geometry)Covering spaceBitQuicksortInternet service providerPublic key certificateData storage deviceParameter (computer programming)File systemTerm (mathematics)Multiplication sign2 (number)Default (computer science)CalculusRange (statistics)1 (number)Variable (mathematics)Computer animation
14:40
WindowCodierung <Programmierung>Scripting languageStrutPoint (geometry)Convex hullFunction (mathematics)Core dumpHost Identity ProtocolPower (physics)Twin primeMaxima and minimaInclusion mapDuality (mathematics)Execution unitAnnulus (mathematics)MIDIScripting languageProcess (computing)Functional (mathematics)Set (mathematics)Parameter (computer programming)Right angleContext awarenessDifferent (Kate Ryan album)Similarity (geometry)Remote procedure callDependent and independent variablesFlow separationNeuroinformatikType theoryInformationInstance (computer science)CausalityComputer animation
22:00
Scripting languageCodierung <Programmierung>AerodynamicsModulo (jargon)Scalable Coherent InterfaceMIDIExecution unitHost Identity ProtocolDenial-of-service attackComa BerenicesWechselseitige InformationFunction (mathematics)Fatou-MengeRippingView (database)Electronic mailing listFile formatModule (mathematics)Arithmetic meanHydraulic jumpInclusion mapConvex hullMenu (computing)Higher-order logicElectronic mailing listModule (mathematics)BitCausalityCountingCovering spaceScripting languageModul <Datentyp>Software developerCASE <Informatik>Inverse elementFunctional (mathematics)Algebraic closureTouchscreenDescriptive statisticsLine (geometry)Element (mathematics)String (computer science)Object (grammar)Computer animation
29:21
Core dumpFunction (mathematics)Scripting languageCodierung <Programmierung>LTI system theoryPersonal identification numberHost Identity ProtocolAerodynamicsModulo (jargon)Proxy serverDemo (music)Default (computer science)Hill differential equationColor managementLimit (category theory)Process (computing)Denial-of-service attackSimultaneous localization and mappingLocal ringConvex hullGraph coloringFunctional (mathematics)Parameter (computer programming)Default (computer science)Goodness of fitQuicksortCASE <Informatik>BitSingle-precision floating-point formatModule (mathematics)Variable (mathematics)Software developerScripting languageObject (grammar)Different (Kate Ryan album)ResultantLine (geometry)Electronic visual displayInformationAlgebraic closureInstance (computer science)Computer animation
34:09
Scripting languageCodierung <Programmierung>Process (computing)Motion blurDemo (music)Computer wormTotal S.A.WindowOnline helpDean numberProcess (computing)Parameter (computer programming)Object (grammar)System callFunction (mathematics)QuicksortContext awarenessType theoryFunctional (mathematics)InternetworkingStack (abstract data type)Default (computer science)Electronic visual displayCheat <Computerspiel>String (computer science)Sound effectComputer animation
37:10
Codierung <Programmierung>Scripting languageException handlingInclusion mapExecution unitSimulationSoftware testingMathematicsGamma functionProcess (computing)WritingObject (grammar)Functional (mathematics)CodeProxy serverGoodness of fitError messageFunction (mathematics)Uniform resource locatorScripting languageYouTubeProcess (computing)Streaming mediaDirectory serviceMultiplication signParameter (computer programming)Level (video gaming)Computer animation
40:39
Coma BerenicesXML
Transcript: English(auto-generated)
00:10
Okay, script blocks. I'm Richard Sidaway, PowerShell MVP. I've written the odd book. Some of them very odd. And oh, yeah, working with Bruce is fun. And director of PowerShell.org,
00:27
I'm responsible for the content for this event. I've been around PowerShell since Beta 1 and version 1. How many people use version 1? Just out of curiosity. Whoa, cool.
00:41
Hasn't it got better? So I'm going to talk a bit about script blocks. When I was wondering what I was going to talk about, because I tend to cheat, I just put my name down and then think about what I'm going to talk later. Because I can, because I do the content. And I was looking through the copy edits for the PowerShell in Action Book, and I sort of tripped
01:09
in my mind that there's a whole bunch of stuff about script blocks that I was vaguely aware of that you could do. And I just thought we'd make a good session. So a lot of it's based on what came out of the PowerShell in Action Book and some of the bits and pieces. I just thought
01:27
it would be a nice session for towards the end that might introduce something new. So first off, everybody know what a script block is? Anybody doesn't? The doors at the
01:41
back of the script block is a, if not the, fundamental PowerShell structure. When you see them, it's basically curly brackets. You call them braces over here? Yeah, okay,
02:00
so braces with a set of statements in it. That's a script block. And you run it and it does stuff. There's some obvious uses that you, where you see a parameter dash script block. So things like invoke command and start job. And then some less obvious ones,
02:26
like for each object, where object, you're using script blocks there. If you're using, certainly in where, if you're using the old style syntax. Any of you use the new module?
02:41
Create dynamic modules in memory? Using script blocks there. The last two, the argument completer and the PSReadLine key handler. I'm not going to get into those today because they are worthy of a topic, a session in their own right, diving into PSReadLine.
03:02
If somebody ever wants to do a session on that, let me know because it's an automatic on the schedule because it's going to be weird, but it's going to be, it would be very interesting. Few other not so obvious ones. You can use a script block in split.
03:20
Anybody done that? One, two. Dynamic modules that I mentioned, so it's in memory. Metaprogramming, I think there was a session on metaprogramming. It's either just been or coming up soon. Yeah. I'm not doing the, I don't know how much overlap there's going to be, but I don't think it's going to be a massive amount. Anybody played
03:42
with steppable pipelines? So you build this pipeline and you can step through it rather than just giving it stuff and going blah. And then the other two bits. Where object I've mentioned, for each I've mentioned. Functions, who uses begin, process
04:03
and end. Cool. Script blocks for all intents and purposes. And then use validate script and then the script block. They're everywhere. Bit like cockroaches. God, I wish I'd thought
04:22
of that when I was doing the book. Bruce would have loved that. Script blocks, cockroaches of PowerShell. Okay. Are you all awake? Right. We'll have a semantic somersault. A script block is the same as an anonymous function. A function, oh you idiot. That's to me.
04:50
Function is a named function. No, I don't mean that. I mean a function is a named script block. Do you know how many times I've looked it? That's got to be changed. You've seen
05:08
me type, you have now seen me type and talk. Not many people have because I don't, I can't. Right. Semantic somersaults. A script block is an anonymous function.
05:20
A function is a named script block. Both are true statements or true-ish statements. Which one is correct? Yes. Okay. Technically both are. I prefer the first. If you note Tobias Weltner from the German MVP who runs the German conference, he was our technical
05:44
editor on PowerShell in action and I lost track of the number of emails that we sent backwards and forwards about this thing. He prefers this. If you want to know why he prefers that, go to Europe and see Tobias. So a script block is an anonymous function
06:07
is the one that I think and you'll see why when we get a little bit further through. If you want to know more about stuff that I haven't covered, I recommend Windows PowerShell in action. I've sort of really got to. Since I wrote it, helped write it and it helps
06:24
feed my children. So please go and buy it if you haven't. If you buy a copy and bring it next year, Bruce will probably be around and we'll get it signed for you. And with that, I suppose I better do some demos. Okay. Script block. So a script block
07:09
is a list of statements in curly braces. So we can create a script block. When I'm
07:24
using them, I always tend to put them into a variable and if you just look at the variable, guess what? You get your code back. Cool. If you want to run it, invoke command.
07:45
These script blocks are deliberately simple because it's a concept. I want to show not all of the mess inside. You can also use the call operator. You all know about the call operator? Anybody not? You do now. Thank you. That's a good line. You don't mind
08:04
me stealing it. The call operator is basically just there to invoke a PowerShell expression for you. I'm going to use that because it's a bit less typing and I was lazy while I was doing this. So look at the function. What's the difference? The function keyword
08:28
and the fact that it's got a name. It's a really explicit name, but uses less electrons.
08:41
We normally just use the function name, which is a difference. You need to be aware of. Call operator works. That's cool. That was one of the, I didn't actually realize that worked until I tried it when I was putting this together. Oh, I wonder if that works. Yes. Oh, why? But you can't use invoke command. There's no invoke command dash function.
09:07
It just doesn't work. So don't try that. If you look at a function, you all know about the function drive? Yeah? So PowerShell has this concept of providers that have
09:25
open up a data store in a similar manner to the file system. So you've got the file system itself, you've got the registry, you've got the functions, you've got variables, you've got environment, you've got the registry, you've got certificates. I think that's it off the top of my head. Big pardon? Yeah, I was coming on to say, and then
09:45
in terms of other functionality, you've got the wonderful AD provider, not, you've got the IIS one, which is, it was good when they first beat us, but it went downhill. There's some weird quirks in the AD one. There's an IIS one, there's a SQL one. Providers
10:08
were a big thing in V1 and it was, the impression we got in the community was that was the way a lot of stuff was going to go. It's one of those concepts that sort of drifted away as the commandlet coverage has increased. So it's the useful, and you'll
10:30
see me playing around with the function. Let me change to side-by-side because that would be easier to see. So when you look at a script block, sorry, when you look at a function, it's got a script block and it's got a name, which we will see.
10:49
So that, that's really the reason why we say that a function is a named script block.
11:00
You can see the script block. Did you know that you can do this? If you create your function, get our function, I've either cut something or copied and pasted that in
11:34
there. All right, we'll keep going. I'm sure it's further down. Looking into the script
11:41
block itself, there's a whole bunch of stuff that you can do with it. So it's got a bunch of methods. One of the ones that you should take a note of is invoke. So you can actually run the script block like that. You can do the obvious and invoke
12:07
it and put it to a variable. You can pass, you've all played with putting parameters into a script block. Isn't that fun? You can do it directly. So default parameters work.
12:38
You know all the advanced function, I'm going to come on to this in a sec, but you know
12:40
all the advanced function stuff that you can do. There's an interesting mix and match as to what works with script blocks and what doesn't, which I'll cover. You can give it parameters or you can use the invoke command and the argument list. So let's build
13:02
our function again. That sort of setup, you know the old style doing functions that everybody says don't ever do this. You can do that with functions, but you can't do it with
13:21
script blocks. You need a param block, which because, as I'll show you in a sec, you can do the same thing with script blocks. It's a much better way of doing it and it's more consistent. And the other difference between a function and a script block is that with
13:41
a function you can actually use the parameter names like dash x, dash y. With a script block you're just using positional parameters every time. You can use parameter validation, which again was interesting. But yeah, the parameter validation, I'm checking the range
14:22
is between two and six and one and five and seven falls outside that range so it fails. So you can actually use a lot of the advanced function stuff in your script blocks. That was scary. And you can use mandatory parameters in your script blocks.
14:55
I'm not saying that this is stuff that you should do or you must do. What I'm trying
15:02
to show you is things that are available that are not as well documented. The script block documentation in about script blocks is basic. And what I'm trying to show you is there's a whole bunch of other stuff that is available that you can use. Should
15:24
you so desire or should it help you to get something done? And as you know with mandatory parameters, they work in script blocks. There are a few things that don't
15:45
work and logically I can see why. So things like parameter sets aren't going to work for you if you try and use them in script blocks. Don't bother trying it because I did. It just doesn't work. You all aware of scope? Oh good. Anybody not? No? All right.
16:10
Scope is basically, it's the context in which you're running. So when you start PowerShell and you're typing at the prompt, think of that as your global scope, the
16:25
something else. It's running in its own scope, but it can access the global scope and you can have two things running and they've got different scopes and if you can pass information backwards and forwards, but if you're trying to use the same variable
16:42
inside and outside, it all gets very interesting because it doesn't work. And that's one of the reasons why the parameter stuff fails on script blocks. If you do that, which I'm going to show you. So with functions, you can do things like that. This, it gets
17:04
the, we're defining the Y variable in the function, but X is taken from the global scope. Invoke script blocks do exactly the same as functions and even with an invoke
17:27
command. You all use jobs? Yeah. Anybody not? Why not? Jobs came in, jobs came in
17:48
PowerShell V2 and I think that one of the best things in PowerShell being able to just kick a bunch of stuff off and run it in the background. Um, very cool. So you've all seen these, I was through these very quickly. So you give a job a script block,
18:10
wait job just waits for it to run and then we receive it and we get rid of it. So let's just to play around with the scope, but let's just modify the script block so
18:23
it tells us what it's doing. So it's got, it's got Y equals six, but it hasn't got
18:41
X because, and the difference here is because when you kick a job off, what's happening? Beg pardon? Yeah, you're in a new process. It's, it's, it's effectively a separate instance of PowerShell that's running that job. So it knows nothing about X and that's why
19:08
it's not picking it up and it's not able to use it. So two ways to get around this, the show off way and the old way. So the show off way is to use using cause that
19:26
means you cool and you've read the documentation and you realize that it came in in PowerShell V3. Basically what that all that saying is using says, go back up the scope and find X and use it or sorry, go back to the original context and where the job started
19:41
and use it. And that's probably the coolest way of doing it. What actually happens a lot is that you parameterize your script block and pass it in and because you've passed
20:18
it in as a parameter, it, it works with it. Remember that when you remoting, you've got
20:32
the similar problem because you, you remoting session is actually running on the remote box, so it's completely different session. It doesn't know anything about X, so it's
20:41
exactly the same situation. So I'm just going to rapidly go through that because it's effectively the same, but just to show that it does use work with remoting. So again, remember arguments, remember using, have you seen the new scope parameter on, um, invoke
21:08
command? I didn't know it was there until I started putting this together. Oh, that's good because that will make life easier. No, it only works if there's no session,
21:22
no remoting session or no computer name. So you running it locally, which means that you're running it in your own scope. So it's there. So I'm not sure what it actually,
21:46
if you try, even if you try it on in a remoting, it blows up because it's a different parameter set. Okay, let's have a string, some well known individuals. I guess you guys
22:06
didn't get Bill and Ben over here, did you? All right. It's a late 19 kiddies program. These two little puppet things live down at the end of the garden and as soon as the
22:21
gardener goes off this lunch, they come out and I didn't quite mean the way you've taken that. I'll stop. I told you I was tired. Okay, so if you, normally if you're
22:49
on split, so let's say we wanted to split that on comma, you would get a, an array with eight elements in it and each, they'd be split on the comma. What about if you want
23:07
to split it by pairs? Oh, Eric and Ernie are two comedians from England, more common
23:20
act England ever produced. So if you want to try and use a script block in your split, you need to set a counter to begin with and then you can split it using the script block. So what you're doing here is saying, I want to split, it's basically scanning
23:42
along the string and the dollar underscore represents the, the dollar underscore represents character coming along the split. So is this a comma and is count after I've incremented
24:00
it, modular two, you all understand modular arithmetic? Anybody not? Excellent. And if that equals zero, which means it's divisible by two, then you split it. So we get Jack and Jill, Bill and Ben, Eric and Ernie, and Cagney and Lacey. And then you can
24:20
see when we're looking count that actually used the counter. Okay. Has anybody played with dynamic modules? Oh, you like this. That wasn't, that was because Bruce said
24:45
so. And it's because you're incrementing it. I, oh, there is a reason. Um, big pardon? Yeah, it's something like that. And I, I'll look at it for you. Remind
25:03
me, drop me a line. I'll look at it for you. I'll post it as to why it's an array. I remember looking it up and I remember, I must remember that because somebody will ask the question and I forgot it's old age. So let's have a look at a, create a script
25:25
block. And one thing I didn't mention earlier is that you can actually put functions inside your script block. So we'll do that. We'll create a new module using the
25:46
script block and we'll, as you would expect, so it works just like a module. So this
26:08
should work. Well, not that line cause it's blank, but that line. Ooh, that's not there, but we can see it because we know it's there. And this is a bit I love
26:28
about dynamic modules. How about that for a module name? Doesn't that just trip off the tongue? If you actually want to see it, you've got to import it and
26:44
then it appears in your module list. If you're playing around with these, a much better idea, let's get rid of that, is to actually give it a name and
27:02
force the import because then it just comes straight up. You see the two commands in the module and we'll get rid of that. Why would you do that?
27:29
Um, cause modules run in their own scope. You might want to push stuff out into its own scope. Um, you might want to be testing stuff and experimenting and this is a quick way of keep, keep doing that. Um, you
27:46
might just want to be having a bet with your mate that it can work. Um, there's a couple of other things that we'll come onto that, that use this under the covers. So it's there. It's, I would use it if you wanting to
28:03
experiment with stuff. It's a, it's a quick way of doing it. Um, or you, you desperately need to separate out the scope, right? Is anybody's head
28:27
going to explode if we go and do a little bit of developer stuff? No. Whoa. Okay. Do you know what a closure is?
28:42
Apart from what it says on the screen there. Therapy. Yes, that's probably the best description you could come up. All right. You know what an object is? It's object is data with methods. Closure is the inverse and it is a function with data attached.
29:02
You can get your heads around that. I'm going to show you the example and then it's one of those things that you probably sit and have nightmares about for the next six weeks and you might just think, Oh, I could use that then. In which case this talk is a, the success. It's really useful when you want to change something. Post the function
29:25
definition. Do you know if you, you create a function and you, um, want to change it, you've got to redefine your function and put it back. You can change this way. You can change it on the fly.
29:43
So let's create a function. We'll go through this. So it's got a single parameter increment, which is defaults to one.
30:01
It sets a variable to zero. It's got a script block, which basically increments count based on the increment and displays count. And then we've got this get new closure, which actually creates the closure.
30:26
So if we create a instance of this in the variable and we get the member,
30:46
it's, it's, we're working with the script block, even though we defined it as the function. And if we run it a few times, it works as we expect.
31:01
So if we create another one with a different counter, a different increment, that's incrementing by two, but our original is still incrementing by one.
31:21
Whereas with functions, you try and trying to do something like that, where you're changing something on the fly. I've got this vague feeling that it's one of those things that could be useful. I'm honestly, I'm struggling to get a true really good use case for it, but it's one of those things that I keep thinking about it, that it's,
31:43
it should be useful somewhere. And I suspect that it's going to be one of those things, um, like if you're provisioning users and you need a function to do something and then you need to change the way the function works, that sort of thing might work for that.
32:01
Under the hood, it creates a dynamic module and all the variables are in the color scope and copied into the new module. Little bit of information for when you load a module.
32:23
This is any script module that you've written. The exported functions are actually closures. So they're actually that, that's how they, they work. And those closures are bound to the module object and the closures, are assigned to the names of the functions to export.
32:44
So they're, they're actually happening under, under the hood. And it's a little bit of developer stuff that I just thought would be really good to blow your mind before lunch. Okay. Uh,
33:01
that's a good instruction. Let's run that. I'll come back and explain this after. Oh, this, yeah. Okay. This is good. Anybody want to guess what this is going to do?
33:28
Would it be cool to be able to do this? I'm picking up the last result and using it. Does that,
33:44
you can actually use it in some admin stuff. Think about this. So let's start notepad. No,
34:04
it's the fact that I haven't actually run the next line yet. You can get the process and you can stop the process.
34:23
Is that useful? Because start process returns, I'm cheating. I'm using positional parameters to do this. So what, what happens is I've got the string notepad that goes into start process as
34:47
the, the, in effect the path to the exceed that I want to start. That outputs a process object which is held in last.
35:01
So when I do get process, I'm actually doing get process for this process object. And then that's effectively get process outputs process object, which I'm then using in stop process to stop that process. Yeah, it's because it's the same thing that it's, it's,
35:21
it's effectively the same object that it's, that it keeps giving. Um, the other thing that you can do with this sort of thing, um, so let's get location. Do you, you're aware of push and pop location? Cool. Um,
35:42
you know, you normally have to type CD, but this function actually recognize that it's a path and uses it to automatically do a CD for you. It'll also work the same if you give it a, um,
36:03
internet uri then it goes off and opens up internet explorer. But the, the internet in here is so flaky that I wasn't going to try that. Okay. Do you want to know how this all works? No.
36:22
Okay. Take two sacks of pixie dust. Okay. So what I'm doing is basically overriding out default. Now you know that if you run a pipeline automatically and invisibly out
36:46
default is tacked on the end of that pipeline, which is why you get the stuff on the display. You also know that if you define a function with the same name as a commandlet, the function is called first because of the precedence of calling.
37:04
So I'm define out default. I really don't care what's coming in. So it's just a PS object which under the hood,
37:22
everything coming out of PowerShell is a PS object. If you trace it down far enough, I'm setting the commandlet that I'm actually wrapping this. This is what's known as a proxy function. So I'm effectively proxying and extending out default. A few years ago,
37:43
Kurt Monroe did a really good session on proxy functions, which I think the YouTube video is still up there. Um, that would be what, 16, 2016. In a script block, I'm picking up the wrapped commandlets and it's bound parameters.
38:04
I'm creating a steppable pipeline, which is probably worth a topic on its own, right? Basically that's a pipeline that you've created that you can step through and stop wherever you want.
38:20
And the important thing about them is they can write directly into the functions, error and output streams. And then we beginning the, uh, command, the, the steppable pipeline in the process. We basically testing to see what is coming through. So if it's an error record, we just check out the,
38:44
the error if it's a directory or a URL and you could add other options in here. Um, I don't know whether it actually worked with the registry, but you, you could, you could force it to and it will go off and move you to the path that you've
39:04
put in. If it's a, um, URL, it'll take, it'll open up your browser and take you to that. If all else fails, it does whatever you you've told it to.
39:21
And it outputs the, um, the output of that command into the last variable. And that's how you create a last object that you can use in your processing work, playing around, confusing people. This code will be available.
39:44
Uh, every time you use it to wind up your colleagues or confuse them, please donate. No. And the code will be available. Um, I'll be home and more or less awake midweek next, next week.
40:02
It'll go up on, um, shed and on GitHub search for my name on GitHub. You'll find it. That is script blocks decoded up to a certain level. There's a ton more you can do with script blocks, but we,
40:20
our 45 minutes are just about gone. I hope it's helped. I hope you've enjoyed it. I hope that you've got something out of it. And thank you very much for attending. Thank you.