Writing Compiled PowerShell Cmdlets by Thomas Rayner

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
doors are closing so that means we should probably get started good morning oh come ye can't all be as jet-lagged and hungover as he sound good morning welcome to summit how you guys doing good so welcome I'm Thomas trainer and I'm gonna teach you about running compiled powershell commandlets in a language you may have heard of called c-sharp who's written anything in c-sharp before sometimes go up okay great you find another nobs game who's written of the hazard didn't go up who's written like advanced functions in powershell stuff that takes parameters mail it binding good alright anybody not in any of the groups that just put their hands up wow you guys might know more than me but i'm up you're talking so you're gonna listen to me i'm a senior security service engineer I work for a small company called Microsoft that's in the area make stuff like PowerShell you may have heard of it and let's keep going are you in the right room so what are we doing what is this session actually like you read the abstract you've read the title you're in the room you're stuck here to close the doors what are we actually doing this is just an introduction to powershell commandlets and c-sharp so if you've written other stuff in c-sharp this is specifically just powershell commandlets we're going to go through four five if we have time but definitely for relatable examples simple examples these are going to be stuff that even I can banging out on a keyboard in front of a room full of people so we're not gonna give you code that oh you're going to take this back to work and it you're gonna implement it right away it's gonna change your life no we're just gonna give you some ideas some examples some building blocks some things that you can use to build your own knowledge from here this is a launchpad so to speak we're doing it in dotnet core which on we're it's not really gonna make a big difference to what we're doing everything is going to be so simple that you're not going to really see a lot of the.net core stuff in play and we're gonna have a ton of fun right first thing in the morning first day or reals sessions we're gonna just have a blast but first one is this not this is not best practices right like this is not a session on how you should organize your project this is not a session on like what you really need to do to make it awesome like I said this is a launchpad to help you learn more this is not necessarily even good practices some of the stuff that we're going to show you is like especially if you've been around the block and c-sharp it's not going to be the most performant solution it's not going to be the most fewest lines of code or anything like that we're in here again just to kind of get you familiarized show you how some stuff works and and see where you take it from there this is not an intro to c-sharp however everybody in the room seems like they're pretty comfortable with PowerShell and syntax like that worked with an interpreted dotnet language it stands to reason you could pick up a compiled dotnet language pretty quickly so I'm not really worried about some of this stuff going over anyone's head we're going to explain stuff as we go so hopefully everyone will be able to keep up and this is not a comparison of C sharp and PowerShell except for one little section then I'll point out this is really just not to tell you you should do this in c-sharp you should do this in PowerShell is to give you another option right Donna and Jeffrey talked yesterday a lot about adding screwdrivers to your tool belt and so PowerShell is one screwdriver c-sharp is another if you want to be able to tackle more scenarios it's worth it to you to add tools to your tool belt also if you're not investing in yourself if you're not learning about new things then what are you doing you must be a little bored and one more thing I didn't make a slide for it this is not easy right there's straightforward demos but nothing that any of you guys do in your day to day work is easy nothing is just do this everything we do is at least a degree of difficulty harder than the average person's going to want to tackle right like it's just a pet peeve when people say oh it's so easy you just do this well just doing this implies maybe years of requisite knowledge so we're going through simple examples in terms of like how far the rabbit hole really goes but it's not just like oh it's so easy anyone can do it anyone can get started and I want to show you how accessible it is but make no mistake about it like none of this is just like pick it up any random person off the streets gonna do it right and these are not perfect demos so kind of like I was touching on the best practices good practices thing hopefully everything goes smoothly so let's get one thing out of the way if you write code you're a dev you take a picture of the slide tweet it whatever if you write code you're in Devon if you don't believe it you're wrong and I'll fight you after this session okay like if you touch infrastructure you're doing ops work you're in you're an operator if you're doing dev work you're a dev if you're doing CI CD work you're a CI CD person it may not be your job title your job title might be technology analyst or systems administrator or a junior dishwasher but if you're doing development work you're a developer that's why I'm wearing my dev shirt dev dot t-- o-- is a social site for developers and stuff I'm a big fan of it but again if you write code you're a dev and so nobody in here should think all I read is PowerShell I'm not a real dev I just noodle around in the console until I make stuff work and then I wrap it in the script and deploy it to prod so then it might not be great development work you might not be in a rockstar turbo ninja guru developer or whatever the latest Silicon Valley titles are but you're a dev you write code you're a dev that's it period so let's talk about why why are we doing this like why what are some use cases for what I'm about to teach you right like what is the actual plan here you could I'm not saying this is the best way to do this but you could write compiled command lists and c-sharp to prevent users from being able to edit your scripts and modules that you deploy to their workstations or deploy to a place that they can read and write them out of this you get out of doing commandlets of c-sharp you get a dll that you can ship around and I don't know if you've tried opening one of those in the text editor lately it's not very easy this is not a replacement for making sure you don't put secrets in your code because like that's still a bad practice no matter what language you're writing it in right but this is a replacement for power user who likes to open it and edit it and then run your script even though they're not supposed to run it like maybe code signing would be a good thing to check into but this is one option if you can't get the other options in there's a few things that genuinely work better in c-sharp than in powershell I know I said this isn't a comparison of C sharp and PowerShell but like a little bit you can't help but look at it right like link I'll show you if we have time asynchronous operations multi-threading who's trying to multi start a PowerShell script put up your hand anyone written like a GUI that they didn't want to freeze anybody had like I want to do this on 50 servers and it takes an hour and a half to run and he didn't want it to take 50 times 1.5 to run you wanted it just to run write multi-threading in my opinion is much more straightforward in c-sharp than it is in powershell there are some great community resources around wrapping run spaces and PowerShell jobs and stuff like that but there's stuff that's native that you don't have to pull a dependency and external dependency on to do it more elegantly in c-sharp working with c-sharp code written by others will show you making a contribution to a small project you might be familiar with will show you working with like a dll that your dev team sent you and yeah you could do some of this in PowerShell if your dev teams gives you a DLL you could work around it and just add types and do things like that but maybe you want to do it in PowerShell instead because you want to challenge yourself or there's another reason that I haven't thought of yet and contributing to other projects I kind of mentioned that in the working with c-sharp code written by others there is a lot of c-sharp stuff on github there's a lot of c-sharp in powershell stuff on github or other public repositories and if you want to play then you got right in the same language right if you want to write a custom PS script analyser rule that you want shipped in the actual product PS script analyzer lets you write PSD ones or PSM ones and use those locally but if you want them to be part of the core PSSA then they need to be in c-sharp and so here we go and most importantly why not man like why not challenge yourself and try something new it's my opinion that PowerShell is a gateway language for traditional system ins and operators and people with those types of job titles to get into more and more development work right PowerShell is in in my opinion really easy to pick up or really straightforward to pick up some guy stop saying easy nothing is easy but it's one of the more friendly languages to get started with everything is very verbose it's not super terse like language like bash or something is or a lot of the Linux executables it's it's dotnet so if you get very familiar with PowerShell it lends itself it's very natural path into learning about c-sharp and learning about other languages that depend on that that working net it's also object-oriented so if you want to start looking at other object-oriented languages that aren't all about dotnet then it's a very natural gateway into doing work like that as well and so PowerShell is a gateway language you start your kind of noodle around in the console your page that you're right you're like hitting f8 all through the ISC that's how you do and then oh it's good save it and then eventually you get some more development practices you become more comfortable you start learning more and more about PowerShell and you go this is great but it does a lot for me and I don't really love everything that it does for me maybe I want to have more control I want to go into a lower level language or I want to go even higher into a language that takes care of even more stuff for me so why not write like you're all here you want to learn so let's get going but before we get going you'll need a couple of dependencies the first is you can do this in Visual Studio code like not everybody has the money or the ability to get a full-blown license of Visual Studio awesome if you do MSDN you can really do a lot with it Visual Studio is an excellent program but vs code is free and the c-sharp extension that goes with visual cuvee s code is free and so you can get started today for free you'll also need the dotnet core sdk right like if you want to develop for c-sharp if you want to develop for dotnet then you got to have the dotnet sdk this meme there is a blue and a green version of Visual Studio code does anyone know what they what the difference is inside these edition that's right I heard a few people the blue one is just a regular stable release of Visual Studio code the green one is the insiders edition and I highly recommend you check out the insiders Edition because it's usually honestly in my experience pretty stable and you get newer stuff faster who doesn't like that it's a little off-topic but there's also an insider's edition of the PowerShell extension that you can go look at I think it's just called PowerShell - preview somebody correct me if I'm wrong yeah you can install that as well and get the new bits in the PowerShell extension faster than the public gets them also and if it doesn't work then you can go harass Tyler on Twitter and tell him all the things that are wrong with it or file a github issue I don't know so now let's actually get started let's actually write some code that's all the real slides that we kind of have here first one line of code to create a new class library we're so this is not PowerShell this is not c-sharp either dotnet is a command line executable basically that takes arguments and does stuff to your computer and the first one that we're running is just to create a new class library a class library is kind of one of the fundamental c-sharp project types this is a template basically that allows you to start writing a new class library and it takes an argument - - name we won't be naming our actual one this today because it's a lie but it's a good demo and if you omit the - - name it'll just create a new class library in their current directory named after your current directory so probably good to do that in an empty directory and it'll create that directory wherever you happen to be and then you can change into that directory then this isn't mandatory but I like to do it in creating a new global JSON artifact in that class library folder that we created this allows you to specify the dotnet core SDK version and so last slide I told you what you needed to get started you need Visual Studio code you need dotnet core SDK there's multiple versions of the dotnet core SDK and if you're doing something that [Music] depends on a certain version being installed because it's a new feature like maybe you need the wind form stuff in there because you're writing an out grid view replacement well then you're going to be dependent on dotnet core 3 so you need to make sure that people developing for this have the right SDK or maybe there's a breaking change that comes in later versions of.net core that you don't want people bumping into so you limit them you do that using this global JSON doesn't take any primer it doesn't have to take any parameters it just kind of goes and then rub a little PowerShell on it adding a package this is retrieving the PowerShell standard library package from NuGet and then it's adding it to our project and that allows us it's kind of like importing a module right like if what we're just doing seeing regular C sharp stuff then we're cool but we want to write a powershell commandlets so we need to get some more goodness in there related to PowerShell some more commands that are related to constructing commandlets and stuff like that there's an alternative you can do dotnet new - I partial a lot of the whole things on the screen this will add a template that you can use for creating a new PowerShell module I personally don't love it the the one that it adds is fine so we're gonna be going the other way instead of this way but this is an option that you could use that was handy and stalling who's ready to do some stuff Oh enthusiasm I love and first thing in the morning anyone still awake all right so let's do some stuff all right we're gonna start with the basics we're literally gonna start with a hello world example all right so what I say we need to do first I'm just doing Visual Studio everybody see that in the back is this yes thumbs up good okay so first things first I'm in a directory it's got some stuff staged for demos that are coming later I'm gonna do dotnet don't net net new last Lib name we're gonna name it hi there okay and it's gonna work flawlessly on the conference Wi-Fi yay and now if we look in our directory again we have a hi there directory it created that for us we're not in the thing we created so we'll actually I'm going to open it in code yes now you could do this - our we'll reuse the same window that you've got open and this will open a folder and I'm sorry yeah in the vs code window if I do that it's gonna reload Visual Studio code and look at me I've got stuff I'm in the hi there folder you guys who've used Visual Studio code are familiar with this cool right I'm gonna pop my terminal open here and make it a little smaller and so what else today so I was gonna do I'm gonna add a dotnet new global JSON this is a great angle to type at with your wrists and I'm gonna do the other thing I said I was gonna rub some power shell on it dotnet ad package PowerShell standard they smell they're right let's find out [Music] no any package your friends I miss Boston somebody go SSL connection could not be established remote certificates invalid I bet it's conference Wi-Fi how are you things are going great there is a plan B but I'm hoping we don't have to use it once again third time's lucky we did it yeah all right so that was all we need to do right done okay short session no let's let's go to work so this is the template that it creates when you just say I want a new class library this is everything it makes for you and we added this global JSON all it does is tell me the version of the dotnet chorus DK that I want to use and we got other full files and stuff here class one CS is raising height if this is a good name for a file raising hand if this is a bad name for a file there you go everybody got it right so I'm gonna rename it to hello world that's us and accordingly I'm gonna rename my class to hello world and now we're just going to start writing some c-sharp I mean I know in my head okay I want to write a PowerShell command lit the PowerShell package to my project so I'm going to make that make all that stuff available to me as I'm writing my code so I'm gonna go using system management automation does that look familiar to anybody system management automation yeah exactly because it's all the PowerShell stuff lives in there right and so that is made available to us because we did the dotnet ad package I'm also going to say this class this hello world class that's command lit and this is wrapped in square brackets you'll be able to see it easier once the highlighting goes away and it takes a couple arguments and you can see them in the intellisense it wants a verb and then it's gonna want a noun does that sound familiar to anybody verb and then a noun right and you know what it should probably be an approved verb too right if only there was like a really easy way to find out what all the approved verbs were you could let go into PowerShell and go get verb right you guys know you can do that and it'll just list out all the verbs you know why that's so easy because there's actually like classes that go verbs common not get and now it's going to be a get I'm gonna say this is my get greeting command late right so the name of this function that I'm writing this command live that I'm writing it's gonna be get - greeting and that's why it's so easy for PS Script analyzer to get mad at you when you use in a verb that's not not one of the approved ones and because this is a command lit that I'm writing I'm going to inherit from the PS command lit class I'm sorry zoom in a bit you bet better that's gonna do cool things here go away go away for real go away some more perfect all right so we're inheriting from the PS command lit class if you're familiar with c-sharp you may have seen this before and you know what this does but if you haven't this is basically saying there is another class out in the wild somewhere probably in here if you had to guess called PS command lit and there are properties and methods which are like functions but they're in c-sharp so they're called methods that belong to the PS command that class that I would like to make available to my hello world class so that's what I'm saying I'm doing there and now all that's left just write some code or something right so let's go let's make a parameter showing it let's go parameter let's accept value from pipeline equals true I didn't put a dollar sign because it's not PowerShell and then if you're writing c-sharp stuff there's snippets built into Visual Studio code and I can go prop and then tab and it's going to insert all that stuff you use snippets in Visual Studio code before probably in PowerShell maybe C sharp and this is going to be just a variable effectively it's called a property but you can think of it like a variable that you use within your within your command and this is a parameter so this is going to be a string I'm gonna call it name and that's all I really need to do and this getting set is c-sharp lingo this is an intro to c-sharp so you have to just trust me that it's necessary and now think of how your powershell commandlets work when you write them in PowerShell what are you writing in like an advanced function after your pram block what comes next begin maybe a process block if you don't want to begin let's write a process block right because besides especially since we're taking value from pipeline we should definitely have a process block right so how do I do that in c-sharp well I override the process block that comes with the PS command let part o protected override void process record and what this is saying is there's a process record method that comes in as just by being a PS command lit object and I'm overriding that with my own definition of what process record is going to do this void is just saying it doesn't return anything because in like in the C sharp world it doesn't return anything we're gonna write stuff out to the PowerShell world but we're not gonna write anything out to like our c-sharp world here I'm gonna go over to declare a new variable and go who that then name it because we're doing best practices right you remember I said no not best practices not even good practices we're so I'm naming that variable that so you can keep track easy so it doesn't scroll for days and that's going to be equal to something you can't do in PowerShell at this time is a ternary expression I'm going to go string isn't all our empty name and then it'll be world if it's empty and it'll be name if it's not c-sharp people maybe you know what I did there PowerShell people who are seeing this for the first time maybe you don't this is much more terse than you're used to seeing in PowerShell I've declared a new variable with a keyword that you don't to use in PowerShell you just go dollar whatever equals whatever and then I've set it equal to is this string name null or empty remember that's my parameter if it's empty then this little question mark between the question mark and the colon gets executed I'm gonna set this equal to world and if it's not null or empty that means I got a value so I'm gonna set it equal to the name so far so good okay and then I'm gonna make greeting and it's gonna be equal to hello hoo dad okay so the string concatenation right probably not blowing anybody's mind maybe you didn't know how to do it in c-sharp but now you know and so this is our hello world example right so I want to now maybe write this out and actually say hello world and so if there's a part I'm going right I'll put oh that's really not working is it but I can go right object and give it that this is just the argument this is just what it's going to write out greeting the variable you could put a string in there and that's cool too and it's gonna write that out to my my output stream I could do there's like write verbose and write debug and other stuff you can do too but I don't want that I want to write output so I saved my file and this is it this is our hello world so let's do let's actually run this wouldn't that be fun wouldn't that be novel who's excited okay and dotnet build that's all it's just the one argument and as long as I don't have syntax errors it'll build and if you read through this output which is very interesting and you should all do every time it tells you there's a dll here that you can import and I'm in PowerShell here so I can go import module and it's in the bin directory debug directory net standard it's called hi there dll because that's the name of my project so that's the name that's the name of my module its name of my namespace import so far so good if I do we get module I can see my hi there module I do a get command and see what's in that module gotta get greeting who wants to run it yeah get greeting yay and you know what else to do we said get greeting we said there was a name oh and it even does that that's the turnery thing going to work here is it empty because I didn't pass it put in world if not put in the name and I also said I could do things like pass values from the pipeline so it's taking the most parameters right so it's a little bit more than a regular hello world where you just hard code everything but that is how accessible it is we did it in just a few minutes here in front of everybody right pretty neat so we did some stuff there's the video that you would all be watching if doing some stuff had not worked well let's do some more stuff right like that was like it would be pretty anticlimactic to end now wouldn't it be a lot easier for me but that's not really why we're all here in this next example we're gonna look at working with somebody else's code specifically in the example that we're gonna look at this is really just where we have a development team and they've given me a dll that I want to use inside of something that I'm writing maybe for my end users maybe for a system I administer and what this thing does that they gave me is it generates ephemeral super top secret codes for access like tokens it's very sophisticated I'll show you the code over lunch if we have time it's definitely not just going to return a random good but the point is this is logic that I can't just recreate myself this is something that's really like top-end and hard for me to work with it's just a dll and they said figure it out yourself there's no PowerShell interface for it there's no module maybe I could work with this thing inside of PowerShell or I could just add it to my project in in a c-sharp environment so I'm going to go code minus R other's code fire that up all right and so I'll save you the creation of the project because you just saw you don't need to see it again but I'll draw your attention to the left side here where we've got a couple things we've got you didn't make me DLL who do you think made that it's not me and oh I can't even open it because this is binary or unsupported do you want to open it anyway probably not so I want to use it inside of my other's code dot CSS file that I've got here and I've already done rub some PowerShell on it I've already added my using statement here I've given it a name it's going to be get secret code and I've left myself a very helpful fantastically descriptive comment this is definitely how you should track all of your work forget like as your DevOps boards or like anything this is how I prefer to do it not so much how do I get my code in how do I use this DLL how do I reference this you didn't make me think using true but before I do that I need to do one thing I need to actually make it available here this system management automation wouldn't have been there if I hadn't have added that package to my project I know I didn't show you that but you had to just trust me trust me I'm a professional I'm a dev okay so I go into my SIA sprog folder I've already added the file to my workspace right like didn't hopefully copy and paste is not above anyone's head here okay yeah it's easy no it's not nothing is easy not even copy and paste but let's take a look at my CS proj file and if you're not familiar there's tons of stuff that can go into a CS proj file but what we're particularly interested in are the packages that we're adding to be made available to us in in the CS files of a running code and in this item group session section that starts on line seven I've got a couple of things here I've got a package reference loop come here package reference on line 8 2 power shell standard library does that look familiar to anybody yes yeah it looks familiar to people ok feedback good and that is put in there because I ran that dotnet ad package partial standard library and it automatically did that for me however this you didn't make me DLL doesn't exist on a nougat repository that I have added to my computer and now what I could do is create a local nougat repository and mess around using nougat dot exe or you probably do it through the net executable as well or you can just reference a local file - and say here's another package the syntax is a little different it's a reference include instead of a package reference include and you have to provide it this hint path to tell it where the DLL is but then after you do that now you can come up here and go using uon even autocompletes isn't this code smart you didn't make me write let's open that back up just a sake of completion there and so now I should probably get to using it and so I've been very lucky my devs don't hate me they've given me documentation on how to use this thing they've given me examples in c-sharp that I'm not showing you because I'm about to just write it out on the screen but there's no powershell example so that's why we're here i'm gonna go what do I want to do I want to go protected override void process record just like we did last time right I'm just creating the process block for my command lit you've seen this already it's all fresh in your minds nobody's that hungover they forgot already and I'm gonna go I need to go make my code and so I'm working from the sample that you can't see and Gove our secret secret code equals and then I know that in this you didn't make me think that there is a fun codes object that I can instantiate and I know that it's static so I can go dot secret code and intellisense really helped me out there right and I could go you didn't make me dot and I can see oh there's fun code so I can go about fun codes and like what's in here oh it's probably that so I can go and start declaring some stuff and now I'm out of the I'm not executing good syntax so in Teleco doesn't like me anymore intellisense but I've worked from my example and I now have a secret code out of my fun codes thing right everybody relatively clear on where this fun codes thing came from that's not native c-sharp it's not part of the PowerShell stuff I got that from you didn't make me and I've I'm just loving the naming convention that my in-house development team used for it and so now like this was really simple in such that it's not doing a whole lot it's just accessing that DLL it's that I added to my project I'm just you've got a using statement here and then I'm instantiating a new fun codes object and I'm extracting the secret code from it because as soon as you construct one over sorry rather it's a static method just go get the secret code and I'll go write object so you could code that's not ominous one like ten people's phones go off yeah so that's all I really want to do here so let's fire up my terminal and go done that build see if I typed everything correctly so far so good and if I go import module bin-debug that standard oops import that DLL and I go get secret code there it is this should just be a string because I've extract the secret code is a string and you know maybe it should be a secure string or maybe it should be something that isn't just piped out to your screen at all but again the point here isn't how to handle secrets or sensitive objects and power in c-sharp the point is to show you how to use dll's that you didn't create and that you don't have the source for that's right yeah if I if I hadn't just got a string out of this I would have got it like a real object right and so sorry yeah so I could do what is it protected override void begin processing and maybe that's where I want to instantiate the thing and then I want to use it inside of here or something and there's a the one that corresponds to the finished but look I can continue accessing my hyper secure environment and getting totally unique tokens that definitely aren't just goods yeah this is all available to me already I could do something like something super useful like that and so this is a good example I can I just import this again mm-hmm I got to build it again and you know what else it's gonna here's something fun I'll show you what breaks dotnet build I kind of spoiled it this is gonna not work and the reason that this is not gonna work is because I imported the thing that I'm trying to build and it's gonna go I am sad that's what this all says it says I'm sad it says I'm sad six times there's a warning and then it doesn't work right and so what do I need to do I need to get the easiest thing to do is just dump this PowerShell process and then recreate it and then just say dotnet build and then it works again yes sorry yeah that's right it comes from up this on line seven and if I go run it again I should have imported yeah and I get my verbose stuff and yeah that's correct where the command like binding comes from so you can write to other streams as well cool all right there's a video you'll be watching if I had failed to remember how to do that so let's do even more stuff let's do some more interesting stuff right like those were relatively straightforward examples right like it was a hello world which is a boy his basic is it gets well though we had a parameter and a ternary expression and then we use somebody else's DLL which is probably way more interesting than the code that we wrote like we only wrote like two lines of functional code in there and where is that DLL probably like 2,000 lines a bit whoever wrote that's probably really smart but one of the things that I kind of touched on is we were going through the other slides in the introduction was some of the quote unquote things that are easier to do in C sharp than PowerShell and one of those things is multi-threading guys I already asked you like who's trying to multi thread something in PowerShell those of you who have tried would you describe it as a particularly exciting and rewarding experience I'm still I've no would you describe it as something that's certainly possible but not really seems like partials not really built for that yeah would you describe it as just like the worst thing in the world it's like slamming your hand in a car door not that bad okay yeah sometimes it depends on how creative you're trying to get so let's take some of the hurt out shall we multithreading it's just like a cooking show what I've prepared for you earlier let's put it in the oven and then take it oh it's already done okay I've got another project this one the CS proj file this is what it looks like when you don't have an external dependency and you're just done ad package command right looks almost exactly the same except it doesn't have that you didn't make me stuff got my global JSON got my dot CS variable here and in here notice it's not a get I'm using the lifecycle verbs I'm using an invoke when should you use invoke like I know there's a real answer but genuinely you know when you should really use invoke it's when you don't know what other verb to use right like there's no like I'm sure it's like you know you ask the people who may let's go get Bruce or Geoffrey and tell them when you should really use invoke but like when should you really use them folk it's just when you can't use another one and so I'm making invoke multi-threading it inherits from the PS command the class I've already written myself a process record here now I'm going to do change my bracing style to fit the rest of the document and to do do a code okay I know exactly what I need to do so we're talking about multi-threading so the first thing I'm going to do just to kind of help illustrate the example because otherwise it's kind of hard to get your head around like how long something takes to run I'm going to do a write object and I'm gonna go started and date time dot now and what that's going to do is gonna write a string out to my output stream of it's gonna start with the word started it's gonna be super easy to identify you're all gonna be like there it is and you're gonna know exactly where it came from and it's going to write out the current date and time of just when this line of code executes right okay minds blown yes totally and then what I'm going to do is I'm actually gonna add a couple more things here using system reading is oops and these are things that will be helpful for us as we begin to do our multi-threading and before I start writing more of my process block I'm gonna do again it's not necessarily the greatest practice in the world but it's what I'm showing you so you're gonna learn it public and long-running task what do you think this is going to do probably gonna run for a while right and it's going to take a parameter called number and it's gonna be a long-running task right I guarantee it and it's gonna sleep for five so five seconds and it's going to return the number that you passed it super valuable everybody take a picture of this and take it home because it's very critical use it and proud of you day if any of you were like have performance tuning based metrics just add a bunch of sleeps to your code and then oh yeah this sprint all I did was improve the the runtime of this module I just make your performance review go easy right so this long-running task is a method it's like a function it's called a method because it's in c-sharp land it's called long-running task it's going to return an integer and it's going to take in an integer and so the integer it returns is the integer it receives all right and now what I'm going to do is I'm going to do like that comment instructed me and I'm going to do a code and then go VAR task 1 equals task run all right so what I've done on line 15 is I've basically just created a new task using this system threatening to attack stuff up here and this is going to execute this long-running task in a thread that doesn't block the one that's running the the rest of my stuff right and so a little bit of weird syntax here that I'm not gonna go over but this is all just running this long-running task method and passing it a parameter of 1 so what's going to give back it's going to wait for 5 seconds and it's going to return 1 and multi-threading isn't really that fun when you only have like one long-running task going on so I'm going to duplicate that line and I'm gonna change this to tasks to make it to you know I'm even gonna do because I'm just so confident we're gonna do a task 3 and so if we were writing PowerShell code which we obviously aren't you would kind of go okay so you're executing this line by line and the system threatening stuff is not really that simple and PowerShell so you're probably looking at a 15 second execution for this task right we're running the thing that sleeps for five seconds we're running it three times but we know because I told you these are all running in threads that aren't going to hurt my overall runtime like that so what I need to do is tasks wait all well that's going to do is it's going to wait for all the tasks that I started to complete and so it is going to block this until all the tasks are done so if these execute sequentially this wait all is going to make me wait for 15 seconds and I tell you it's gonna be so awkward as I just stand up here for 15 seconds it's gonna feel like way longer than 15 seconds I'm telling you okay especially while you're waiting for it and then for closure I'm gonna do right object finished okay and so we're writing out the date and time that we started we were and we're writing out the date and time that we ended so hopefully the dates the same but the time if everything went right should only be five seconds later and if things are not being multi-threaded just to prove the concept it's going to be super awkward as I kill 15 seconds on stage and it'll be 15 seconds shown to us on the screen so you do a dotnet build I'm gonna import the module muscly I'm gonna go invoke multi-threading hmm that was weird what happened there finished immediately oh you know what I do need to do I'm gonna go they can't be done already I'm gonna go VAR output equals a put plus I'm gonna task 1 dot result whatever came out of that + space let's keep it like that plus that's to that result + space and then I'm gonna yes I was just about to cover I'm so good at typing and talking at the same time so yeah what I've done here and it Scrolls off screaming but I think you get the idea I've created a new string here a new variable and it's just going to be the output and then it's going to be the result of task 1 the result of task 2 and the result of task 3 because they didn't come anywhere else it got swallowed by these task variables right so I'm gonna kill that we're gonna import again that looks better started come on oh that was better than having to wait 15 seconds for it wasn't it so started at 9:49 27 and it then he gave me my output the one two and the three you guys know where that came from right that came out of this long-running task that we did that's the only place that could have come out of right and then it finished the same day impressive five seconds later yeah question yeah yeah insofar as it writes to the output stream everybody okay question yeah yeah like if I'm not doing anything with it it's just saying okay you're done like you don't need to wait for any of these results you're just free to to move on there's no dependency on the output from that stuff parish will make you wait anyway right yeah instead c-sharp just scares the crap out of you and goes you're done and you go what the heck are you talking about so yeah there's a lot of alternatives for things that you can do here and like there's lots of different ways to do multi-threading as well and c-sharp like this isn't just one solution that kind of looks nice on the screen because the whole thing only takes up thirty three lines you could use you could use run spaces if you wanted you could use seen before as you could do a whole other stuff but this is kind of the simplest for a lot of people to kind of get their heads around when they're first getting started right so we're doing great on time which means we can do the demo that I wasn't sure we'd have time for that's a collection I know find out that the best way to learn by trying so if I take out this output I'm just gonna write actually you know what we'll look at collections in one second here because the demo that we could have cut was linked so I'm going to add this link example here and take a my scaffolding with me and I don't need that and I don't need I was holding shift don't need that don't need change this to link whoops is that the link type of correctly the first time all right so I was just very sloppily set up a new CS file in the same project and I've named it invoke link and I've added this link I've done this using systems link expression by the beginning here who knows what link does a couple of hands more or less it makes working with collections of objects happier and you're going to see in this example I could have done that using select object and where object and you'll be right because these are simple examples right but link is super powerful and in some cases in most cases more performant than typing stuff into where object and select object and sort object and stuff like that and it's normally normally fewer lines of code that when you're doing more elaborate expressions as well and so this is just going to be a quick little tour of some of the things you can do with link not necessarily all the things you can do with link or all the things that you should do with link but let's let's get out of I'm in my process block again like I could do some of this outside the process block but I'm choosing not to and I'm gonna go var list one there's gonna be a collection back door and they're gonna go in numerable range so what this is and I want to do a to list so what this is doing is it's going to create a new list of integers not an array not an array list but like a list list this is a object if this is a type of collection that you don't normally see people write in PowerShell but it is pretty objectively better than the types of collections that you normally see in PowerShell I'm sure if they had it to do over again syntax like this where you redo that obviously this is not gonna be happy in my c-sharp project dollar thing you all zap brackets I'm sure I bet I bet I'm not sure but I bet if they had that to do over again they would make that a generic list or something but they didn't so I think I'm other than Nick blood next thing I'm gonna do is make another list and I'm gonna start this one at five and so the other thing I'm using here is this innumerable dot range that's gonna create me basically a range of numbers and it takes two arguments this is saying start at one and then give me the next ten numbers and then turn that into a list and this is going to say start at five give me the next ten numbers and then turn that into a list or sorry give me ten numbers starting at one give me ten numbers starting at five not and then give me and so I'm going to get in this one a list that goes 1 2 3 4 5 really and the next one I'm gonna get one that goes in so on and the next one we get a list that just starts at 5 and then goes for 10 okay everybody happy yes good and now let's start using some of the link stuff let's go far only one and I want to get the numbers that are only in list one not the ones that are in list two and you would go I can do that in PowerShell using where object I can write a filter script that does that you you're right you can or you can use a link expression you can go a list one except let's do that's going to give me all the numbers that are in list 1 that aren't in list 2 and likewise I can go and get the numbers that are in list 2 but not in list 1 right that's interesting you could do that maybe with something a little more elaborate than numbers you can do that in a way where this isn't just as straightforward as you're seeing it here you can do more elaborate objects that you're trying to separate into different collections but there's more we can go list or show a VAR what do we want to do let's go in both lists one oops it's a lower case case sensitivity matters here list one Union let's - oh yeah and that's not what I want you know let's make this all unique Union is going to give me all of the objects in both of these lists but it's going to give me a unique list so that's going to be like piping in to select object - unique except you're not gonna pay the pipe line tax for doing this so perhaps this is more performant than what you're doing with select object or maybe it's just a list of numbers and is gonna perform about the same either way but maybe this is like a list of 500 million objects and all of a sudden trying to put those through the pipeline matters a little more than it used to right and so let's do in both like I was going to do you know list one oh I forgot my equals list 1 dot intersect that's two and so this except like a kind of mention is going to go get all me that get me all the stuff that's in less - except the stuff that's in list 1 cool the Union is joining these two collections together and it's implied that you understand that it's going to return unique objects this intersect is saying basically give me all the stuff in list 1 that intersects with the stuff that's in list 2 everybody just trust me we don't need to run it doing no ok let's run it let's go right object and let's go list1 and I could just go let's just try this first to satisfy the question from earlier and let's just go with this one plus and let's just run this first right like this isn't testing all the stuff that we made this is just showing what happens when you write that list out let's do a dotnet build and let's go import module bin-debug that's standard multi-threading because this is still the multi-threading project right they just cuz I'm doing the link stuff I'm still in this multi-threading namespace I'm still in this multi-threading project that this is all being wrapped up as one module and again one of the things I'm not doing wouldn't it be cool if I had like a PSD one in here that told you like the commandlets that I was exporting and maybe had a copyright and stuff like that I'm also obviously not doing comment based help which you can do in here this is a different syntax I'm not sure we'll get to what I'm gonna import that whole module and if I do a get command on that module I got invoke link and I've got invoke multi-threading so in the VOC link handy right that's what you wanted you wanted the name of the type of object and it doesn't that kind of remind you of PowerShell in a way where when you like just take like a hash table or an array or something and you just well not an array it'll figure that out but like a hash table where you put it just in quotes inside a string and it just tells the system does collections that hash table and you're like no kidding right so we need a more elegant solution or more realistically a more complicated solution so what I'm going to do is because it still want it labeled list 1 what would you do in PowerShell parentheses around it maybe you would use a join to get it all on one line especially because we're gonna be doing one two three four five six of these and I don't feel like scrolling that much on the touchpad so I'm gonna I'm gonna join stuff like impartial you go join and then you go wait it's not PowerShell so we're going to go to string join and that's a method that we can use and it tells me oh what do I need to do because you would normally go I'm gonna put the collection and then join and then the thing that I want it to join on and then you would look at this and go wait it's backwards I need the separator first which is going to be a comma in a space and then the enumerable thing what is the fit what is the collection and I'm going to go list one so I'm taking all the stuff in list 1 and joining it using that as a separator and to save a little time it's also do two and let's also do what was this one this one was actually you know it would be easier and less prone to typos you guys know about like this multi cursor stuff and yes code yeah there's a different truck I think it's ctrl shift alt and then the arrow keys will do like a block selection ctrl alt up and down yeah I've changed mine just to shift alt which is what it is in a lot of other places but you can do like what I'm doing here and select a block of code and start typing and overwrite it there so that's kind of handy yeah that's right so yeah let me find an example here so like if I started this line and I go like that watch where my cursor goes I'll go control arrow and it goes just to the end of that word even though they're at different columns and then control arrow to the other side of the equals and you can kind of see it moving through here even though they're not lined up in a column anymore it's still just sorting it out for me which is nice yeah there's a few ways to get to that output I highly recommend and again this is a little off topic but we're doing pretty well going to everybody this we're gonna shift alt a comments it out for me but I've screwed with my bindings and just to show you you can go into your keyboard shortcuts and look at the mall and you can even go I don't know what's happening when I hit shift alt and then my arrow or whatever page down or what and it'll search the key bindings or you can go how do I do like multi cursor toggle do multi cursor modifier etc so that's a bit of an aside maybe I already knew that about vs code maybe you didn't and then why did the other ones I need I need one for all unique whoever the next door is just killing it both you guys want to compete now let's hear okay well if this works just give me a big deal you're all gonna applaud right okay when you bring this back let me get rid of that let me bring it back in and go that build and you know if I remembered how to do this all right by memory and I didn't screw it up and it was actually kind of impressive import my module and do an invoke link the sort of God here I told you the truth I got in list one one two three four five six seven eight nine ten starts at 5 goes to 14 only in 1 1 2 3 4 and that's right because as soon as we hit 5 we start overlapping only in - well we overlap until we get to 11 all the unique values 1 2 3 4 5 all the way through 14 and then the ones that are in both 5 6 7 8 9 and 10 oh please please that'll teach him but the point remains this was not super complicated in in c-sharp right if you know what you're doing oh here's all my link stuff it was just to get all the stuff that was unique to one list unique to the other list all the unique values the values that overlap like there it's built for you which one yeah sorry this I'll explain again this innumerable dot range is going to give you this many numbers starting at number five yeah so it doesn't give you a beginning and an end it gives you a beginning and how many you want he says yeah yeah like if I was doing this for real I probably include like a PSD one and a PS upper one and stuff like that and make like a real module out of it and then I would have this stuff that goes with it you know genuinely off the top my head I'm not sure I I'm certain that there is a way to do that I'm just I can't grip it on off the top of my head in the moment but tweet me and we'll figure it out together any other questions about like this demo the next one is fun so you might not want to know what like if I wanted to use like I'm like a PowerShell module that I'd written or something like that you can do it but it's not necessarily the most beautiful thing you've ever seen and in fact why are there any other questions about this first no why don't we show you a great example of how a c-sharp and powershell work together not by watching the video that you would have seen if I had just fallen dead onstage but let's add something stupid to PowerShell car don't you want to do that like you remember yesterday everybody stayed and listened to like all of the keynote talks that we had where they showed you how valuable the community was to PowerShell right and they thanked those people for going and triaging issues and adding pull requests and like who remembers the percentage for how many of the PRS against the PowerShell repo come from the community how many was it 50 over 50 right that's a lot and you know why that matters because honestly the PowerShell team is not huge you would think like oh it's a roomful of people like this who are all guys you're like really smart and nerds in front of a laptop Open Office right just like this and they all just write code all day no it's not like you can count them on both hands kind of thing of the people who work on this product that we all love and depend on and so they really depend on the community for contributions and that's why PowerShell core has been such a success so let's join the club and now after this you'll all be able to join that Club and ago and it's gonna work so quit spoiling it by the way if you wanted to find out how to make cool prompts like this without pulling any external dependencies I've got a another session this week Wednesday no Thursday afternoon on how to build a neat crap like that it's a little bit less formal than this but there's the most formal as I get so let's take a look at the folder I just opened shall we it's big let's just look familiar to anybody what's this look like it's the PowerShell repo this is the code that you get when you do a git clone HTTP colon slash slash github.com slash pile or whatever the rest of it is don't get and it's got assets not interesting today demo is darker docks docks are probably a good place to go source and it's also got like a build PSM one so we're probably not gonna run just done that build on this we're gonna use the build tools and if you want to get started with this if you want to get to the point where I'm at right now basically where I've just got it all ready to build there's excellent docks on the website if you go see if I can pull it up on the fly dot-com go to their it is chromium edge guess what it actually works really well because it's just chromium without a lot of the Google stuff pull out of it yeah and I know like I work I work for Microsoft right so it's pretty natural that I'm gonna try it I highly recommend it it's pretty neat I've been using Chrome extensions in chromium edge but I can also use edge extensions which is handy if you use both and like one of the things I'm using is this dark reader thing look at this github dark theme you know how to do that it I don't believe a thing right I could turn it off and oh I hate myself I could turn it back on and now it's all it takes a crack at making a dark theme and so anyway if you come down here there should be contributing developing and contributing please see the contribution guide etc we can go in there and it's going to tell me intro to get and github good place to start Quick Start checklist make sure you've done this stuff get familiar with the repository have fun good luck it's big contributing to issues contributing to docs contributing to code use vs code you can build PowerShell this is how you do it etc so you can see somebody has gone through a lot of trouble to write excellent getting started documentation that takes a lot of the what the heck and why the heck out of getting started with developing the PowerShell project and so because I know where I'm going I'm going to expand the source folder and navigate immediately to the PSD one for the Microsoft PowerShell dot utility module let me things got weird at big resolutions if I do a get module you know let's do get module I've got just by default I just reloaded this session I got my chocolaty stuff you guys should check that out if you haven't shut its TV Microsoft I Parish hold up management and Microsoft up ouch all got utility and then PS read line right I haven't loaded anything in here so this is just what comes when you start having fun with PowerShell so I'm going to go to if I can find it again the PSD one for that module isn't just another module right so it stands to reason that it would have a PSD one and it works better when it's not gigantic somebody has added something suspicious see them yeah it looks like you'd want it in PowerShell core right to this ladies and gentlemen is core functionality that you can look forward to no but this is the only change to this file that I've made and I can make this change because I cloned the thing locally right I've made get - cat fact so you know what I should probably do now make a command line that gets a cat fact and so I didn't have the self-confidence to write this in front of you all live so pardon me for that but I'm using some of the networking stuff using some JSON stuff I'm making a class for cat facts this is a real project and so we don't want to just futz around with some strings it's going to have a fact and a length because that's what the API is going to give me it's going to create a new cat fact this is a constructor we haven't talked about those yet but if you've developed classes in any language you may be familiar with the concept of a constructor it's how you create a new cat fact in this case it's going to make sure that the length of the file that we got matches the length that it says it should be why well because sometimes the API that I've chosen screws up it gives you a fact that's not as long as it thinks it is and it's a big mess so we'll throw an error in that instance and we're not doing C sharps or we're not doing partial stuff yet like this isn't the command lit this is just a class but if we get a bad fact back from our API we're going to throw a fact wasn't the link specified error otherwise we're gonna make a new fact that says fact of length right okay and now my pride and joy my baby no just a command lit called get cat fact that has a help URI of cat a fact ninja and an output type of cat fact and it's gonna inherit the get catified command it's gonna inherit from PS command lit this is all stuff that we've pretty much seen like the output type is new but you're familiar with that kind of thing for PowerShell not blowing any minds right get cat fact is going to do a fact URL this is how this is the API that we're hitting and it's going to do few things that to be honest I'm not entirely sure necessary because I stole this code from someone in this room Stevie thank you i modified it a little bit so that it worked it was in progress it's not his fault but yeah thanks I hope you help me in the future yeah but I'm just creating a new httpclient like this is where you might go man this would be so easy in impartial I can do an invoke rest method hit the thing and be good yeah maybe but it wouldn't be in power salt pork if you did that so let's let's get at her some cool stuff to the headers we're sending our user agent when we're gonna go get string async off of the fact URL converted to a URI and then we're gonna put the result into the result variable this is all like 41 through 46 it's all just getting it's hitting that API basically right easy enough to read and then we're gonna construct a new cat fact of type cat fact from the D serial I basically converting that to JSON because it's going to give us back basically a big string and we're gonna be say hey that string is JSON and I know that because I've examined the API and read their Docs and so I need to convert that to JSON or to an object really that I can work with and return it that's what get cat fact does and then my process record the process block itself is going to get a new list of cat facts in this case it's just going to get one cat fact and it's going to isolate the fact variable or the fact property I should say you guys remember because it comes back with a fact and a length we just want the fact because who cares about the length we just use that for troubleshooting and then we're going to write it out to the output stream and then life will get fun because I'm gonna go import the build module I think it was start PS build and this will take a long time compared to the ones that we were making and it's almost like this is a much bigger project than the ones that we were working on and that it's kind of hard to get familiar with and so most people and I you know maybe that even includes people on the team as well are pretty familiar with some areas of the language like not everybody works on all the stuff and that goes also for people in the community like mark who is pointed out rightfully yesterday for his excellent work on the web commandlets correct me if i'm wrong mark not an expert in the parser as well exactly if you couldn't hear him he said heck no people who are super smart about how the tokenizer and everything works not necessarily super familiar with all other areas of the project right that's kind of makes sense for how a big project works so as you're diving in yeah it looks kind of hard to get started with but that's okay because you have time and I encourage you once you start kind of looking through some of the parts spritely stay away from the tokenizer and the parser and stuff unless you're a masochist like you guys remember yesterday joel who got one of the community awards Joel oh if you want to hire them go to hire Joel dev if you want a higher Joel yeah but if you want to be like Joel dive right into the tokenizer in the parser and really regret your life decisions or you can do something smart like hey there's this command lit that doesn't work like I think it should work so I'm gonna go try to improve that so you can come try to find where it is like you can look through the list here as we're looking through the utility thing or I've added my get catfac CS you can also see here's where you the enable and disable see a PS breakpoint commandlets are here's where the CSV commands are here's where convert to HTML lives oh I bet this is where the web command lets live you want to go screw with mark stuff I don't but you can get started in such a way that doesn't have to be all at once right it'd be like drinking from a fire hose not that fun so this is finished building and all I saw was green and white text so it must have worked and I'm going to run this version of PowerShell that I just built right like I just built a version I'm gonna run my only exists on my laptop version of power sha cuz I forgot to do a git push I'm gonna do run so this get PS output just tells you where your the thing you built lives like this is where I stored my PowerShell repo and then this is the path to the belt executable and I'll go mmm I haven't rebased in the wall so it's a little out of date because I was afraid of breaking my demo but this doesn't look like a regular version of PowerShell does it this doesn't look like a regular version of PowerShell does it I have all my basic modules there could be nothing fishy or weird or entertaining going on with this version of PowerShell that I've built right in front of you let's just take we got time let's go get command module Microsoft they parish opt-out utility let's just look I just have a gut feeling let's look at the get the ones that start with get Oh looks pretty normal variable type data breakpoint do you trust the Wi-Fi as much as I trust the Wi-Fi oh that was a bad one checkin hey a female cat is called a queen or a Molly but you didn't know that if you learned one thing at this session take back to you in your job a female cat it's called a queen or Molly I want to go again there are approximately 100 breeds of cat did you know that I didn't know that smell of cats cat lover is called today I learned I'm aware they can't pronounce won't last 100k its second last one okay I fight Tigers are excellent swimmers and do not avoid water so if you're ever being chased by a tiger you're screwed you're not gonna add swimming around climate you just f'd but the other important thing to see what's going on here is the AAPI that I chose was really simple to work with but also sometimes gives me back bad data and that's why we're getting value cannot be null parameter name fact it wasn't the length specified does that look familiar fact wasn't the Lynx though specified argument null exception right value cannot be null argument all exception primary I'm Sarah pretty cool so all that's left for me now is to add some unit tests and then create my a pull request toddler that'll be fine right you can get the you help me get that approve today yeah maybe I should pick an API that's a little more reliable but that's how you can add not only stupid things that censored weirdest things that's how you can add stupid fun stuff to PowerShell that you may be a distributing in-house that's how you can give back to the community that's given me and probably all of you so much by helping improve the product that we all depend upon and came to a conference to talk and learn about so highly recommend check it out you don't have to be a rockstar deaf who bought a shirt that says dev on it - or an imposter that bought a shirt that says dev on it to go contribute to this project or any other c-sharp project or deride c-sharp commandlets that exists just in house for you there's the video you would have watched if I had decided not to do this because I got bored and that is basically my session so I'm open to questions you can find me on Twitter the other links there are very fun for you as well one thing I do want to point out real quick the powershell discord and slack those ak8 on ms links i highly recommend you check that place out if you're looking for like-minded individuals who enjoy PowerShell it's very welcoming and helpful community it's full of people that just seriously sit around all day and do nothing but try to help you and come up with ideas for new PowerShell related stickers and it's it's a great place to be whether you like this court or slack I'm Laurel side author I've written some books as well if you want to learn about as your automation go check out my Pluralsight courses otherwise thank you very much for spending an hour and a half with me talking about C sharp and powershell commandlets I hope that you have learned something valuable that you might bring back with you to work otherwise I hope you're at least entertained a little bit thank you again for coming [Applause] [Music]
Info
Channel: PowerShell.org
Views: 8,596
Rating: undefined out of 5
Keywords: powershell, windows powershell, techsession, powershell summit
Id: O0lk92W799g
Channel Id: undefined
Length: 88min 11sec (5291 seconds)
Published: Sat May 18 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.