Powershell - Illinois Institute of Technology
PowerShell
• Windows PowerShell is Microsoft's new shell and scripting language
• PowerShell is similar to the traditional command prompt except it’s much more powerful - “It is a batch files on Steroids”
• PowerShell requires .NET Framework 2.0 or higher to run since it is built around .NET interfaces
• More than 100 cmdlets (pronounced "command-let"). Each can interact with other commands
• Some of the improvements from Windows PowerShell include:
- An updated and consistent scripting language
- Intrinsic regular expression capabilities
- The ability to call into the .NET Framework, WMI extensions, and the Windows registry
Your first seven steps to learning PowerShell
1. Download PowerShell (Get an OS specific version)
2. Begin with familiar old dos commands: dir, CD or Ipconfig (Just to get comfortable)
3. Make a collection of verb-Noun pairs, e.g. set-Executionpolicy and get-Childitem
4. Call for help with get-Help wmiobject and master get-Member
5. Create lots of scripts or Cmdlets
6. Deploy the Pipe symbol | (Join commands | filter)
7. Master $_. This construction means the current object in the pipeline.
For example: where | {$_.name -contains "Microsoft"}
Examples to type at the PS prompt type:
get-command
get-command get*
get-Eventlog system
get-Eventlog system -newest 100
get-Eventlog system -newest 100 | where {$_.eventid -eq 20}
List only services that begin with the letter 'w' and sort them by status
[pic]
“set-location data” is the same as the old command “cd data”. Command “get-childtem Pow” means lists the contents in the current directory which start with "Pow". Windows PowerShell is not case sensitive, so you can type Get-ChildItem or GET-ChildItem.
[pic]
PowerShell itself
Key point, you need to download an operating specific version of PowerShell. Windows 2008 has version 2.0 PowerShell. Microsoft provides slightly different version of PowerShell 1.0 RTW (Release to Web) for:
• Vista
• Windows Server 2003
• XP
• For Windows Server 2008, there is an easier technique: install PowerShell by launching the 'Add a Feature' option in Server Manager.
PowerShell default setting
- You cannot simply run it by double clicking it
- You can run only scripts that are signed and trusted by your system
- You must always run by explicitly enter the path – prevents malicious hackers
- Four execution policies are available:
* Restricted (Default) No scripts are allowed
* AllSigned Only signed scripts are allowed
* RemoteSigned Locally executed scripts are allowed
* Unrestricted All scripts are allowed
To view your current execution policy, run this command;
Get-ExecutionPolicy
To set you execution policy to RemoteSigned, run this command;
Set-ExecutionPolicy RemoteSigned
Some sample commands
Get help on command Get-ChildItem.
Get-Help Get-ChildItem
Use –full switch to get full help file for a particulat command.
Get-Help Get-ChildItem -full
Show running processes
Get-Process
Show running process and sort by ID
Get-process|Sort-Object Id
Display list of services
Get-Service
PowerShell Structure
First program
1. Use notepad or textpad to write a program below
# This is a comment line
$str = “Hello World”
write-host $str
2. Save the file with extension .psl example; c:\helloworld.ps1
3. At the Windows PowerShell prompt, enter
powershell C:\helloworld.ps1
Variable names
$MyName = “James Bond”
$x = 5
${Variable name with space} = “Use the curly bracket”
$a = 2
write-host ($a +2) # prints 4
$a = “Steve”
write-host ($a + 2) # prints Steve2
[string]$str = “Some string” # using type casting
[int]$a = 2
Write-host ($a +2) # prints error
Variable types
[boolean]
[int]
[char]
[string]
[double]
[datetime]
Dim myArr(2) # Array contains 3 elements. Index starts at zero
myArry(0) = “first”
myArr(1) = “two”
myArr(2) = ‘three”
write-host $myArr # prints all content in one line
$myArr = $myArr + “fourth” + “fifth” # add more array elements to array
Conditional statements
$a = 5
if ($a -eq 1) {
write-host “One”
}
elseif (4a –eq 2) {
write-host “Two”
else {
write-host “Anything”
}
-eq Equal to
-ne Not equal to
-notmatch Does not match
-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less or equal to
switch statement
$color = “blue”
switch ($color) {
red {write-host “Color is red”}
yellow {write-host “Color is yellow”}
blue {write-host “Color is blue”}
default {write-host “Color not in range”}
}
Loops
For ($i=1;$i –le 100; $i++) {
}
Foreach ($ in $) {
}
Foreach ($file in $Get-ChildItem C:\Windows) {
}
$i = 1
While ($i –lt 11) {
}
$i = 1
Do {
} while ($a –lt 10)
write-host “Done!”
PowerShell in Action
List all services currently running
Get-Service | foreach {if ($_.status –eq “Running”) {write-host $_.Displayname} }
System Variables
$_ Contain the current pipeline object
$? Stores return code of previous command execution – true if succeeded
$Args Array of parameters passed to function
$home User’s home directory
$host Current host information
List Processes running on your machine. Get the operating system processes, and then groups them by company name. The code is a work-in-progress, so output the data to a file called ProcessCompany.txt.
# PowerShell cmdlet to group Processes by company
$Path = "C:\PowerShell\ProcessCompany.txt"
$ProSvc = get-Process |sort company |ft -groupby company
$ProSvc
# $ProSvc | out-file $Path
Result: You should see a list of processes grouped by Company name.
• Copy the code into a text file
• Save the file with a .ps1 extension, for example: addcontenta.ps1
• In PowerShell, navigate to the folder where you saved addcontenta.ps1
(D:\PowerShell\Files in the screen shot below)
• Issue this command:
.\addcontenta
(dot backslash filename)
Stop the World Wide Web Publishing service. Using Windows PowerShell you can issue the command:
stop-service -servicename w3svc
or, in shortened form:
spsv w3svc
Suppose you want to view running processes sorted by the number of handles owned by each process:
get-process | sort-object -property handles
$p = get-process
$result = $p | measure-object -property handles -sum -average -max
$result | out-file '.\ProcessHandleStats.txt'
$p = get-process, fetches all the information about processes currently running on the host machine, and stores that information into variable $p.
$result = $p | measure-object -property handles -sum -max, sends the captured process information to the measure-object cmdlet which computes the sum, average, and max value for all the handles in use by the currently running processes, and stores that information into variable $result.
The third line, $results | out-file '.\ProcessHandleStats.txt', saves the results to a text file.
If you examined $result at this point, you see something like:
Count : 54
Average : 273.148148148148
Sum : 14750
Maximum : 1625
Minimum :
Property : Handles
Notice that in this example there are a total of 54 processes running, and a total of 14,750 handles in use, which is an average of about 273 handles per process. The largest number of handles used by a process is 1625 handles.
or, in shortened form:
gps | measure-object handles -sum -average -max |
out-file '.\ProcessHandleStats.txt'
# Display the filename and its size
foreach ($file in get-Childitem)
{
$file.name + " " +$file.length
}
# PowerShell foreach loop to display files LastAccessTime
"File Name " + "`t Size" +"`t Last Accessed"
foreach ($file in get-Childitem)
{if ($file.extension -eq ".txt")
{
$file.name + "`t " +$file.length + "`t " + $file.LastAccessTime
}
}
References
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- seton institute of reconstructive surgery
- michigan institute of real estate classes
- sports institute of tucson
- institute of physics iop
- institute of physics uk
- american institute of physics
- american institute of physics citation
- american institute of physics inc
- chicago institute of plastic surgery
- indian institute of public health
- nigerian institute of international affairs
- eric institute of education science