Monday, December 15, 2014

PowerShell Tips : Setting Requirements using #Requires.

 

This is a very cool PowerShell Tip and I am sure that you are going to love it.

There are few script which you want to Run as Administrator and you want to set dependency that the script should only works if the PowerShell console is running in a elevated /administrator mode, other wise  it should not run.

How you are going to  set this dependency? think think ... using a function? that will be complicated.. then ?

Ok!! the answer is , using #Requires

In the top of of your script, type :

#Requires -RunAsAdministrator

That's all. save the script and then try to run the script in admin mode and in normal mode and you can see the difference.

Let's see the example.

In the below script, I have added only two lines of code. , in first line we set the Dependency using #Require to execute the script only if it is running as admin.  and in the next line, we are just using the Write-Output cmdlet to write the text  "I am running as Administrator"

Let's save the script and run it.

12-12-2014 11-42-12 

I am running the script in normal windows  PowerShell console session,and you can see that it throw the error.

12-12-2014 11-40-45

Now, let's run the script in elevated mode, and you can see below, this time it run as expected, without throwing any error.

12-12-2014 11-41-29

 

12-12-2014 11-41-49

Video :  You can see the video of it.

Setting Requirements using #Requires.
There is lot's more which we can achieve using #Require. To know more about #Requires read the help
PS C:\> Get-Help About_Requires
15-12-2014 17-16-42
I have tested this in PowerShell V4.0.
Thanks for reading the blog and viewing the video.
Regards.
Aman Dhally
If you like, you can follow me on Twitter and Facebook. You can also check my “You Tube channel for PowerShell video tutorials. You can download all of my scripts from “Microsoft TechNet Gallery”.

Murky_ana

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.