In this section we are going to have a look over using .NET object properties and methods in Powershell.
Powershell uses .NET Framework objects at its core. For example, we get the current date in Powershell as below:
Cmdlet Get-Date actually contains DateTime object underneath. To Prove this, Use the command Get-Date along with Get-Member, you will find list of members of DateTime object. You can also use Get-Date in the manner we use objects in C# in order to access the properties and methods as shown below:
Here, we have accessed Day property of DateTime object. In the screenshot above, being in parenthesis, Get-Date is executed first and on top of the result, ‘.Day’ is executed to retrieve the day. We can access all other properties in the same manner. Similarly, we can call methods on the object in the same way as shown below:
Here, we have added 5 days to current date by using AddDays() method of DateTime object.
Being able to handle objects in this manner can be very useful in certain scenarios. For example, let’s say you are writing some Powershell script to automate some task and you want that task to execute after some days/years/months and you want to do this repeatedly. You can then use the DateTime object in above stated manner to set the execution time for the task and leave the rest to Powershell.
Similarly, we can use Get-Process to get the objects related to currently running processes.
As shown in above screenshot, we have first started notepad application and then using Get-Process and Get-Member, we have listed all the methods and properties related to running process notepad.
Now, in the screenshot below, we are stopping the process notepad and then trying to list out the members which results in an error as the process has been killed already.
In the same way as Kill() method we can execute all the other properties and methods related to any running process using Get-Process method.
Note: You can pipe Get-Member cmdlet along with any object in order to get the list of all the supported properties and methods for that particular object.
E.g. Get-Date | Get-Member