Run Tasks on Timers in PowerShell

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Great video!

One thing that was nice to learn is how to see constructor overloads:

[System.Timers.Timer]::New
πŸ‘οΈŽ︎ 7 πŸ‘€οΈŽ︎ u/Szeraax πŸ“…οΈŽ︎ Dec 13 2020 πŸ—«︎ replies

Cool, there are times I cant set a scheduled task on a server and having it be contained in the script would be easier

πŸ‘οΈŽ︎ 4 πŸ‘€οΈŽ︎ u/evillordsoth πŸ“…οΈŽ︎ Dec 13 2020 πŸ—«︎ replies

Hey folks, my latest video covers the topic of creating timer-based tasks in PowerShell. Please let me know what you think of this topic, and share something useful you've created with this concept! I'd love to hear what interesting applications you've discovered for PowerShell. 🍻

πŸ‘οΈŽ︎ 4 πŸ‘€οΈŽ︎ u/pcgeek86 πŸ“…οΈŽ︎ Dec 12 2020 πŸ—«︎ replies

Why not use Task Scheduler?

πŸ‘οΈŽ︎ 2 πŸ‘€οΈŽ︎ u/Nosa2k πŸ“…οΈŽ︎ Dec 13 2020 πŸ—«︎ replies

Thanks, this seems like it will be very useful!

πŸ‘οΈŽ︎ 2 πŸ‘€οΈŽ︎ u/biglib πŸ“…οΈŽ︎ Dec 13 2020 πŸ—«︎ replies

Excellent video. I finally learned how to subscribe to a YouTube video!! Thanks for that!!

πŸ‘οΈŽ︎ 2 πŸ‘€οΈŽ︎ u/RoRoo1977 πŸ“…οΈŽ︎ Dec 13 2020 πŸ—«︎ replies

Great training, as always.

It seems PS is updating so fast, it seems hard to stay up to date at times. How do you do it?

πŸ‘οΈŽ︎ 2 πŸ‘€οΈŽ︎ u/StreborNodnal πŸ“…οΈŽ︎ Dec 14 2020 πŸ—«︎ replies

You shaved the beard!?

πŸ‘οΈŽ︎ 1 πŸ‘€οΈŽ︎ u/StreborNodnal πŸ“…οΈŽ︎ Dec 14 2020 πŸ—«︎ replies

I'm sure there are some use cases where this might be needed, and the video does a good job at explaining how to do it.

But anytime you are reaching into the clr to make use of a timer in a powershell script, I have to think, you need to reevaluate if what you are doing needs to be a powershell script.

Just because you can, doesn't mean you should, something like this should be a windows service or utility, and in the example provided one should likely make use of a directory watcher, and trigger in changes, and not do checks on a timing interval.

As a rule of thumb I would not recommend making use of objects that require disposing in powershell, there are way too many ways that script can be terminated and you end up on probably disposing of the unmanaged resources that object maybe using.

If you are going to use the CLR like this, I would recommending learning. .Net or specifically c#

πŸ‘οΈŽ︎ 2 πŸ‘€οΈŽ︎ u/ExceptionEX πŸ“…οΈŽ︎ Dec 13 2020 πŸ—«︎ replies
Captions
hi guys my name is trevor sullivan and welcome back to my channel if you have not yet subscribed to my channel please consider hitting that red subscribe button down below and if you click the bell icon next to it then that will help get you notified anytime that there is a new video on my channel now for today's topic i wanted to talk about powershell yes powershell once again that seems to be where i always kind of default to it's just where my comfort zone is i suppose i do learn a lot of other technologies but i'm not always necessarily at the point where i want to build training content around them however what we're going to do in powershell today is actually take a look at how to register for events asynchronously and specifically we're going to create a timer and then we're going to basically trigger a task or an action or a powershell script block that we want to run every time that that timer elapses so think about maybe wanting to clean up a directory of files every five minutes or something uh if you see any stale files in there you just want to wipe them out and let that directory repopulate with some task that's running somewhere else so let's switch over to our desktop here where i've got microsoft visual studio code running you're not using visual studio code to develop software regardless of what language you're using you might use powershell you might use python you might use c-sharp or anything like that visual studio code is a versatile editor for pretty much any of those languages so definitely recommend checking it out and if you are using vs code specifically with powershell if you hit ctrl shift x and search the extension marketplace for vs code there is an excellent extension here called the powershell extension there's also a preview version of it so i would recommend installing the preview version personally because that tends to have the latest and greatest features the latest and greatest bug fixes it's not perfect but it's it's pretty good so if you're still using the powershell ise or something like that then i would recommend checking out the powershell powershell extension for visual studio code i'll hit ctrl b just close the sidebar there and what i'll do is just hit ctrl n or you can just double click in this empty space to create a new file in vs code and if you hit control k followed by m you can change over the language mode to powershell so that you get syntax highlighting intellisense and all that kind of stuff also i've got the integrated terminal open here and i think i am running powershell core edition in here yep powershell version 7.1 ps edition core so all good there so let's go ahead and create a dummy directory for now so i'll go ahead and just go to my root here and down here in the terminal and i'll do maker temp 2 and if we cd into temp 2 you can see it's an empty directory you can do dir ls gci they're pretty much all the same thing get child item that's the powershell way of listing out items in a directory and what i'm going to do is just create a couple files so do you set content path path not pass through test1.txt value law then i'll just hit up arrow tab over or control arrow over rather and create another file called test2 so now i've got these two text files in this directory here so now what i want to do is basically clean these up but i want to do that on a timer so let's say maybe every 15 seconds we just go into this folder and just clean it out and let it repopulate maybe you're i don't know taking screenshots or maybe you've got some kind of um some kind of task that's just writing you know inventory data and you want to make sure that inventory data is up to date whatever the task may be let's just pretend that we want to clean this up so to clean this up is pretty straightforward we would do get child item dash path c temp 2 star so if we do f8 sure enough we can see that this line is going to return us the files in that directory and because we are specifying the absolute path here we can go ahead and just go into any directory so if we're at the root of the c drive this command obviously still returns the contents of the seed temp to directory now in order to delete those files we would need to do we need to pipe them into the remove item command and then i don't want to actually remove them yet i want to just kind of test this out so i'll use the what if parameter which in powershell is kind of a way to test out what would happen if you were to run a command instead of actually executing the command so if i hit f8 you can see i get this what if output saying performing the remove file operation on target test1.txt test2.txt so this command if i just remove the what-if parameter will actually do the cleanup operation for me so now what we need to do is actually set this up to run on a timer every let's say maybe 15 or 30 seconds whatever interval you want is totally fine so what we need to do is to create a timer and this is all pretty well documented in the net framework documentation so go check out docs.microsoft.com i think docs.msdn.microsoft.com perhaps and that will show you all of the right commands to run i'm actually just going to go ahead and open up a new browser window here let me bring that right over here and let's just head over to google and we will search for net timers and in the system.timers.net namespace there is a class called timer so this is what we're going to be using in powershell to actually create the timer so you can see the c-sharp example here but we're going to be using powershell to instantiate it instead so normally in c-sharp you'd have to do a using statement say using system.timers and then you can instantiate a timer somewhere down here so down here they're doing new system.timers.timer which is kind of weird because if they're if they're using that namespace they don't actually need to specify the full name space to it but whatever um anyways we're basically just going to instantiate it so let's take a look at the constructors here so you can instantiate a timer with no parameters or you can instantiate a timer with a different constructor a constructor override called with that takes a double parameter and that double is the interval so it says this constructor sets the interval property but does not enable the timer so basically we're going to construct a timer but it will not be enabled from the get go so we actually have to start it explicitly once we are ready so that's how we instantiate the timer however we also need to register for events on the timer so that when the timer elapses or when the timer ticks basically every time depending on which language you're familiar with it might be a tick it might be elapsed whatever but in.net if we take a look at the events over here on the sidebar let me move out of the way there really quick so there's events and then what we're going to do is take a look at events and we have disposed and disposed is a pretty standard.net event on a lot of different objects because basically when the.net garbage collection process runs and an object is disposed you can register for those types of events um actually when yeah so when the dispose method is called on that object you can you can uh certainly register for that event that's more of an object life cycle event whereas what we're more interested in is specifically the timer event which is this one right here elapsed so basically every time that the timer ticks or elapses rather then we are going to kind of hook into that event and run some powershell code to clean up our directory so to create this object you can do a couple of different things if you're on an older version of powershell you might want to do new object dash type name system.timers.timer and if i hit f8 you can see that creates a new timer object down here in my terminal however there is a more kind of modern syntax to do this uh which is system.timers.timer and then there is kind of this implied it looks like a static method because when you use a double colon after a net type that typically means that you are calling either a static method or you are referencing an enumeration value if the type is a system uh sorry a dotnet enumeration but in this case this timer is a net class and because it has constructors on it we can simply call this new method on it which you won't see in the documentation but this is more of a powershell specific way of instantiating an object so you can see that we have either the new with no parameters or we have the new with a double interval so if i pass in let's say 15 000 this is going to be the value in milliseconds that we want our timer to operate on now in order to actually use the timer as you saw down here when we called new object it just spit that object back out to the output of powershell and it's not actually assigning it to a variable so if i wanted to take this object and call the start method on it to actually trigger the timer to work i can't do that because i don't have a variable to reference this object so what we need to do is when we instantiate the timer assign it to a variable so that we can then reference it later on to manage it so i'm just going to comment out this line that has our get child item command piped into remove item because we don't want that to run right at the moment so now that we've created this timer object in this timer variable you'll see we get this little help text saying hey the variable timer is assigned but never used it also shows up here under the problem section which is useful so it's actually a ps script analyzer static analysis rule that's telling us that and so basically what we want to do is hook into this timer and grab the elapsed event so i'm going to hit f8 to define this variable timer in my console here and now if i do timer and pipe that into get member get member is an introspection command that allows you to inspect an object to see properties methods as well as net events that you can hook into and sure enough you can see that this timer object has the elapsed event that we saw over in the documentation as well so what we're going to do is use the powershell command called register object event and this is really powerful because you can basically register for any event on a.net object by using the register object event command and then i'm just going to do a powershell restart current session because the extension just gets hung up and intellisense stops working randomly hopefully they'll fix that someday but now that it's back up and running i can add in the input object so this is the object the dotnet object that you want to register for events on so i'm going to do dollar timer and then i'm going to specify the event name parameter and this is the elapsed event that we want to hook into of course and then the last parameter we need to specify is dash action and if i just hit the down arrow here and hover over action you'll see that the value of the action parameter is going to be a powershell script block also known as an anonymous function in some other languages and basically this is just going to be a block of code that runs every time that our timer ticks now for the sake of demonstration i'm actually going to take this from 15 000 milliseconds down to maybe 3000 milliseconds just so it ticks a little bit more quickly here and what i'm going to do is uncomment this get child item remove item command and move that into the action block here so basically every time that our timer object elapses every three seconds three thousand milliseconds we're going to run this action here so i'm just going to do a quick ls on c temp 2 and sure enough those files are still there so now if i hit f5 to run this script you'll see that i get back this event registration here now the last step in this process even though we've registered for the timer elapsed event we haven't actually started the timer so if i just inspect that timer variable here you'll see that enabled is false and that's because when we instantiated the timer it doesn't enable it by default so what you need to do is do timer dot start so there's a method on the timer object called start that's over in the dot net documentation as well i'm sure let's head over here come back to the timer class and if we go over to methods right here on the right hand side i don't know if i'm pointing at this correctly right here then that'll take us over to the methods a lot of these are just kind of standard.net methods that are inherited from other classes however if we scroll down you see there's a start and stop method so we can basically turn the timer on or stop the timer when we are done so if we switch back here i'm just going to hit f8 on this line here and the timer has now started so if i wait just a couple of seconds here and then do an ls on c mp2 oh my gosh our files are gone so maybe i'll just do set content dash path c temp two test.txt dash value blah and then i'll do get child item after that and if i select this and hit f8 to run just these two lines here actually i need to do get child item c temp 2. there we go so now you can see that i've got this test.txt file but if i just hit f8 to run get child item again that file magically disappears because our timer is running this is how you can basically run a task on a timer using your powershell now if you wanted to kind of launch this as a service you could actually use something like the windows task scheduler that basically just runs this powershell script so you could do something like pwsh dash file you know see scripts timer.ps1 if you saved all this into a file called timer.ps1 you could actually just put that in there however what would actually happen is after the timer started it would actually exit the script and so that powershell process would die so what you can do is run this command called wait event and then if you run weight event dash take a look at a help for it source identifier is the parameter that you want to care about here and so if you do wait event dash source identifier some id that doesn't exist if i hit f8 this weight event command is going to pause the script execution until it gets an event some id that doesn't exist and because that event is never actually going to be triggered unless you have some other code that is actually going to send that event to powershell then this event will never actually get triggered and it will just cause your script to pause indefinitely and your timer will still continue to run so that's all you really have to do to create a powershell script that you can then run as a service you could configure it to run at startup using a startup event trigger in the windows task scheduler so it's kind of a poor man's service scheduler but it works right anyway i hope you enjoyed this video feel free to go ahead and head out to cbtnuggets.com if you would like to check out my training we actually have a free service as well now so you can actually sign up for free over at cbtnuggets.com all you need to do to sign up for a free account is to have a google account so that is the only prerequisite but once you have a free account you can view a whole bunch of free training about things like desktop support devops introduction to programming systems administration we've got some aws training content as well i've even got a free skill here as well called send windows notifications with powershell that helps you to send windows 10 notification toasts so definitely head over to cbtnuggets.com and sign up for our free training account thanks for watching and we will see you next time take care
Info
Channel: Trevor Sullivan
Views: 3,839
Rating: undefined out of 5
Keywords:
Id: 8dZbdl3wzW8
Channel Id: undefined
Length: 17min 8sec (1028 seconds)
Published: Sat Dec 12 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.