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.
If this script is saved to “c:\powershell\check_memory.ps1” then it can be run from the command prompt by typing:
However, life is never quite that simple.
That’s because PowerShell does not automatically allow scripts. It actually has four levels of security (known as execution policies):
It will, in all likelihood, return “Restricted”. It’s then just a matter of setting the execution policy to be less restrictive:
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
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
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
Read on
powershell c:\powershell\check_memory
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 <<<<
- 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)
powershell get-executionpolicy
powershell set-executionpolicy RemoteSigned
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