Getting Started with PowerShell
- · Install power shell in your XP machine. In Windows 7 it is present by default. Download is available in the Microsoft Site. http://www.microsoft.com/download/en/details.aspx?id=7217
- · launch PowerShell in start -> run by typing powershell
- · Now let's a write our first script to modify the dates of the files present under the folder "C:\PowershellTest\testFiles" to current date and time plus 5 minutes on each file.
- · Create a txt file and rename to "MyFirstTest.ps1". Edit the file with the below code. It adds the current time to the first file and adds another 5 min to the each file.
-----------------------------------------------------------------------------------------
# getting the current time
$Now= Get-Date
# Listing the files and folders under the folder
$TargetFolder = Get-ChildItem "C:\PowershellTest\testFiles"
# For loop , variable must be preceded with "$"
foreach($file in $Targetfolder)
{
$file.LastWriteTime = $Now
# Adding 5 min
$Now = $now.Addminutes(5)
}
# Displays output
$TargetFolder
-------------------------------------------------------------------------------------------------------------------------------
- · In PowerShell, ALL variable names must start with the "$" character
- · "#"is used for comments
- · You can debug the script using the powershell editor (powershell_ise.exe) which is already part of the application.
- · Open command prompt and type powershell.exe. It will open up a power shell window. The result would be as shown below.
PS P:\> C:\Powershelltest\MyfirstTest.ps1
Directory: C:\ PowershellTest\testfiles
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/27/2011 8:26 AM 0 New Bitmap Image.bmp
-a--- 7/27/2011 8:31 AM 12800 New Microsoft PowerPoint Presen ion.ppt
-a--- 7/27/2011 8:36 AM 10752 New Microsoft Word Document.doc
---------------------------------------------------------------------------------------
First Issue:
First Issue:
File MyFirstTest.ps1cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing"
Reason: The security setting does not allow you to execute a script, by default the Execution Policy is set to Restricted. This is the so-called Execution Policy
There are 4 policy levels:
- Restricted: Individual cmdlets can run, but not saved Powershell scripts. This is the default setting.
- AllSigned: Scripts can run, but must have a digital signature even if written on the local computer. Prompts you before running scripts from trusted publishers.
- RemoteSigned: Scripts written on the local computer do not need a digital signature, but any script downloaded from outside (email, IM, Internet) must have a signature to execute.
- Unrestricted: Any script can run, but scripts downloaded from outside will run with a warning.
To change the Execution Policy to Unrestricted, type the following command in Powershell
Set-ExecutionPolicy Unrestricted