Thursday, October 7, 2010

Powershell

Powershell Tutorial is available at http://www.powershellpro.com/powershell-tutorial-introduction/

How to Write a PowerShell Script
Reference : http://www.suite101.com/content/how-to-write-a-powershell-script-a115669


There are no restrictions as to where the scripts are placed on the computer, but they must always have the same file name extension - .ps1.

An Example PowerShell Script

The best way to learn about scripting is to examine a real example, in this case a script that will:
  • list all running processes that are using more that 1M of memory
  • ignore the PowerShell process
  • sort the result
  • place the result in a file formatted for viewing on a web site
The script is quite simple, although it is worth noting the use of pipes (represented by |). Pipes allow the output of one Cmdlet to be used as the input to another:
get-process |
where-object {$_.WS -ge 1048576} |
where-object {$_.processname -ne "powershell"} |
sort-object WS –descending |
convertto-html -property Name,WS > c:\Inetpub\wwwroot\ps.html
If this script is saved to “c:\powershell\check_memory.ps1” then it can be run from the command prompt by typing:
powershell c:\powershell\check_memory
However, life is never quite that simple.

Enabling PowerShell Scripts

Anyone running a PowerShell at this point will probably receive an error something like:
File c:\powershell\check_memory.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
At line:1 char:26
+ c:\powershell\check_memory <<<<
That’s because PowerShell does not automatically allow scripts. It actually has four levels of security (known as execution policies):
  • Restricted: This is the default execution policy, and stops all scripts from running
  • AllSigned: Allows scripts to run, but only if they have an associated digital signature from a trusted publisher.
  • RemoteSigned: Allows all scripts on the computer to run and any other scripts that have an associated digital signature from a trusted publisher
  • Unrestricted: Allows all scripts to run (but this should be avoided)
The current execution policy can be examined from the command prompted:
powershell get-executionpolicy
It will, in all likelihood, return “Restricted”. It’s then just a matter of setting the execution policy to be less restrictive:
powershell set-executionpolicy RemoteSigned
The script can now be run and the results examined in the HTML file that it produces.


Read more at Suite101: How to Write a PowerShell Script: An Introduction to Automating PowerShell http://www.suite101.com/content/how-to-write-a-powershell-script-a115669#ixzz11gSjWgZD

No comments:

Post a Comment