Powershell Quick Reference Sheet Page 2

ADVERTISEMENT

What’s New in PowerShell 3
Requirements: W2008 R2 SP1, W7 SP1, .NET 4.0, download and install KB2506146 or KB2506143.
Note: install ISE first before upgrading to PowerShell 3 on Windows 2008 (R2) or Windows 7!
Automatic module loading: no need to use e.g. “Import-Module ActiveDirectory” anymore.
ISE changes: IntelliSense, brace matching, error indication, start snippets, rich copy, block select (Alt+Mouse), context sensitive help (F1), many more!
New modules: BranchCache, DirectAccess, Dism, DHCP, DNS, iSCSI, NetAdapter, NetTCPIP, NetworkSecurity, PKI, Printing, Schedul ed Tasks, SMB, Storage, many more!
$PSItem
# same function as $_: current item in pipeline
Show-Command
# shows a GUI for a specific Cmdlet
Get-Process
|
Out-GridView
-OutputMode
Multiple
|
Stop-Process
# Out-GridView has an OutputMode parameter: select several items and press OK
Install-WindowsFeature
WindowsPowerShellWebAccess
-IncludeManagementTools –Restart
# Installs PowerShell Web Access feature
Install-PswaWebApplication
-UseTestCertificate
# creates the virtual directory and appliation pool using a test certificate
Add-PswaAuthorizationRule
* * *
# Creates an authorization rule. Now browse with any supported browser (IE, Chrome!, Firefox!, Safari!) to
Looping
for
($i
=
1;
$i
-le
10; $i++) {
$i
}
# displays numbers 1 through 10. See the Active Directory section for a practical example
While loop only executes when condition is true
Do … While loop, always executes, at least once
Do … Until loop, always executes, at least once
$i
=
1
$a
=
1
$a
=
1
While
($i
-le
10) { $i;
$i++
}
Do
{$a; $a++}
While
($a
-lt
10)
Do
{$a; $a++}
Until
($a
–gt
10)
Typical example of a Do … Until loop
$RequiredLength
=
12
Do
{
$password
=
read-host
-prompt
"Password, please"
if
($password.length
-lt
$RequiredLength) {
"password is too short!"
}
}
Until
($password.length
-ge
$RequiredLength)
Functions
Function
Get-NewestEventlog
{
Param
($log=”system”,
$newest=5)
Get-Eventlog
$log
–newest
$newest
}
Get-NewestEventlog
# try with parameters like –log application –newest 10
WMI
Get-WmiObject
–list
# lists all WMI classes
# inspecting shares through WMI
# automating defragmentation (please check with your SAN administrator!)
Get-WmiObject
Win32_Share
$Cvolume
=
Get-WmiObject
Win32_Volume
|
Where
{ $_.name
–eq
"C:\"
}
$share
=
Get-WmiObject
Win32_Share
|
Where
{ $_.Name
–eq
“C$”
}
$df
=
$Cvolume.DefragAnalysis()
# can take several minutes or even hours
$share
|
Get-Member
# check name and caption
$df
# inspecting the result
# we’ll need the wmiclass type to create objects through WMI
If
($df.DefragRecommended) { $Cvolume.defrag($true) }
$share=[WMICLASS]"Win32_Share"
$share.create("C:\", "mynewshare",
0)
# creating a new share
Get-WmiObject
Win32_OperatingSystem
–computername
(Get-Content
servers.txt)
|
Format-Table
__SERVER,Version,ServicePackMajorVersion,ServicePackMinorVersion
Get-WmiObject
Win32_LogicalDisk
-Filter
'DriveType=3'
–ComputerName
(Get-Content
computers.txt)
|
Format-Table
__SERVER,DeviceID,FreeSpace,@{Label='PercentFree';Expression={$_.FreeSpace
/
$_.Size};FormatString='{0:#0.00%}'}
Active Directory
Requirements:
PowerShell v2, Active Directory Module for Windows PowerShell (on a Domain Controller, also part of RSAT). Open port TCP/9389.
Requirements:
Windows Server 2008 R2 Domain Controller or install ADMGS on a W2003/2008 Domain Controller.
Import-Module
ActiveDirectory
# imports the Active Directory module for PowerShell
Get-Command
–module
ActiveDirectory
# displays all 76 commands in PowerShell v2
New-ADOrganizationalUnit
“Employees”
-Path
"DC=Contoso,DC=com"
# creates a new OU
Get-ADOrganizationalUnit
-Filter
“*”
|
FT
Name,
DistinguishedName
–AutoSize
New-ADUser
TestUserA
# creates a disabled user in the Users container
# The next script takes a plain text password as input and creates an enabled user account in the Employees OU
$userpwd
=
ConvertTo-SecureString
-AsPlainText
"Pa$$w0rd"
–Force
# converts plaintext to secure string
New-ADUser
TestUserB
-AccountPassword
$userpwd
-Enabled
$true
-Path
'OU=Employees,DC=Contoso,DC=com'
For
($i=1;
$i
–le
10; $i++) {
New-ADUser
–name
Testuser$i
}
# creates ten new testusers
Background Jobs
Remoting
Start-Job
{
Get-Process
PowerShell
}
Requirements:
PowerShell v2 on local and remote systems. Enable Remoting on
Get-Job
remote system. Open port TCP/5985.
Get-Job
-Id
1|
Receive-Job
# use the -Keep parameter to keep the data in memory
Enable-PSRemoting
# Run this on the remote system. Use –Force optionally.
Start-Job
{
Sleep
60
}
# starts a new job which just waits for 60 seconds
Enter-PSSession
–ComputerName
Server2
Wait-Job
-Id
3
# wait for a job to complete, or use: Stop-Job -Id 3 # stops job
# use your PowerShell skills now on the remote machine
Remove-Job
-Id
3
# remove a completed job
Exit-PSSession
Free ebook about remoting:
Error handling and Debugging
$ErrorActionPreference
# displays the default action when an error occurs
Dir
c:, x:,
c:
# should result in a file listing of the c-drive, followed by an error, followed by a listing of the c-drive
$ErrorActionPreference
=
‘SilentlyContinue’
# or ‘Continue’ or ‘Inquire’ or ‘Stop’
Dir
c:, x:,
c:
# should result in two file listings of the c-drive, no more error
# Use the –ErrorAction parameter to use a other error action for the current command only
$Error[0] |
Get-Member
# displays information about the last error
More information on the Internet (and the previous page…)
survival-guide.aspx
This document is licensed under a Creative Commons Attribution-NonCommercial-NoDerivsCC BY-NC-ND license.

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 2