您的位置:首页 > 运维架构 > Shell

PowerShell 2.0 学习笔记

2014-05-06 13:39 417 查看
学习书籍 : 《 Windows PowerShell 2 For Dummies 英文版》

1. $Mystring = " windows powershell "
$Mydouble = 2.0
$outsting = $Mystring + $Mydouble
write-output $outstring
$outstring = [string]$Mydouble + $Mystring
write-output $outstring
Trace-Command -Name TypeConversion -pshost {[string]$Mydouble + $Mystring }

2. Set-Variable PI 3.14159265 -option Constant
Set-Variable Author " Steve Seguis " -option Readonly
$radius = 3
$area = $PI * $radius & $radius
write-output "Area is: " + $area
write-output "this book is written by: " + $Author
Remove-Variable Author -force

3.
$firstname = "Dan"
$lastname = "Daman"
$fullname = $firstname + " " + $lastname
write-output $fullname
write-output "length of full name: " + $fullname.length
write-output "full name is : " + $fullname.ToUpper()
$newname = $fullname.replace("good","bad")
write-output $newname

4.
$a =1 ; $b=2
($a -eq 1) -and ($b -eq 2)
($a -eq 1) -or ($b -eq 2)
($a -eq 1) -xor ($b -eq 2)
-not ($a -eq 1)

5. -lt -le -gt -ge -eq -ne -is -isnot -like
-notlike -match -nomatch -contains -notcontains

6.
$a = 6
if ($a -gt 5) {write-host "greater than 5!")
$a = 1
if ($a -ne 0 ) {write-host "non-zero value entered")
if ($a) {write-host "non-zero value entered."}
$name = "steve"
if ($name -eq "steve) {write-host "hello steve"}
else { write-host "hello anonymous" }

7.
$size = "M"
switch ($size)
{
"S" {write-host "small"}
"M" {write-host "medium"}
"L" {write-host "large"}
"XL" {write-host "extra large"}
default {write-host "unknow size" }
}

8.
for ($i =1 ; $i -le 5; $i++)
{
write-host $i
}

9.
foreach ($i in Get-Alias)
{
write-host $i.name
}

10.
$objrandom = New-Object Random
$i = 0
while ($i -ne 6 )
{
$val = $objrandom.Next(1,33)
write-host ("one of six red boll:" + $val )
$i++
}

11.
$objrandom = New-Object Random
do
{
$val = $objrandom.Next(1,33)
write-host ("got number" + $val )
} while ( $val -ne 7)
write-host "finally,you got 7"

12.
$objrandom = New-Object Random
do
{
$val = $objrandom.Next(1,33)
write-host ("you got a " + $val)
} until ($val -eq 7)
write-host "finally got 7"

13.
Get-Process | Where-Object ($_.Id -gt 1000) | select-object Name,CPU,ID | sort-object CPU,Id

14.
Get-wmiobject win32_bios
get-wmiobject win32_computersystem
get-wmiobject win32_bios -computername REDLINE

15.
win32_bios
win32_computersystem
win32_directory
win32_logicaldisk
win32_networkadapter
win32_networkadapterconfiguration
win32_ntlogevent
win32_operatingsystem
win32_printer
win32_printjob
win32_process
win32_quickfixengineering
win32_registry
win32_scheduledjob
win32_service
win32_share
win32_timezone

16.
get-wmiobject -query "select Manufacturer,Version From Win32_BIOS"

17.
Get-wmiobject win32_service | where-object {($_.startMode -eq "Auto" ) -and ($_.state -ne "Running")} | select-object DisplayName,Name,State

Get-wmiobject Win32_NTLogEvent |Where-object {($_.LogFile -eq "Application") -and ($_.Type -eq "Error")} |
select-Object Cateory,ComputerName,EventCode,Description,Message,TimeWritten | Sort-Object TimeWritten

18.
Get-Wmiobject -calss iiswebinfo -namespace "root\MicrosoftIISv2" -computer web01 -authentication 6 | select-object MajorIISVersionNumber,MinorIISVersionNumber | Format-List

19.
Invoke-Wmimethod -path "win32_service.name='w3svc'" -name stopservice
Invoke-wmimethod -class win32_process -name create -argumentlist "c:\program Files\Internet Explorer\iexplore.exe"

20.
$str = "This book is fantabulous!"
$str.split()
$myIp = "192.168.0.1"
$iparr = $myIp.split(".")
write-host ($iparr[0] + $iparr[1] + $iparr[2] + $iparr[3] )

21.
$myip = "192.168:10;101"
$iparr = $myip.split(",:;")
write-host ( $iparr[0] + " " + $iparr[1] + " " + $iparr[2] + " " + $iparr[3] )

22.
$test = "the sky is cloudy!"
write-host $test.substring(4,6)

23.
$str = "steve is evil"
$newstr = $str.replace("evil","lala")
write-host $newstr

24.
$email = "someone@dummies.com"
$atpos = $email.Indexof("@")
$user = $email.substring(0,$atpos)
$domain = $email.substring($atpos+1,$email.length-($atpos+1))
write-host $user
write-host $domain

25.
$username = "testuser1"
[RegEx]::IsMatch($username,"testuser[0-9]")
$username = "anna"
[RegEx]::IsMatch($username,"ann[ae]")
[RegEx]::IsMatch("food","[^fh]ood")

26.
\d any digit from 0-9 [0-9]
\w any digit,uppercase,lowercase letter and underscore [A-Za-z0-9_]
\s white-space characters (space,tab,new line,and carriage return) [ \b\t\n\r]
\D not a digit , opposite of \d
\W opposite of \w
\S opposite of \s

[RegEX]::IsMatch("SRVWEB1","SRV[A-Z0-9]+")
[RegEx]::IsMatch("SRV1","^SR[A-Z]+[0-9]")
Match must occur at the beginning of the string, use ^
[RegEx]::IsMatch("SRVFILE1","SRV[A-Z]+[0-9]$")
[RegEx]::IsMatch("TESTSRVFILE1","SRV[A-Z]+[0-9]$")
[RegEx]::IsMatch("SRVFILE1TEST","SRV[A-Z]+[0-9]$")
The opposite of the caret symbol is the dollar sign $, which is used to perform a match at the end of a string.

[RegEx]::IsMatch("domain.com","[A-Za-z0-9]+\.(com|edu|net)")

27.
$email = "somebody@domain.com"
if ($email -match "[A-Za-z0-9]+@domain.com")
{
write-host "$email is a domain.com email address"
}

28.
$str = "visit us at www.domain.com"
$newstr = $str -replace "www\.[A-Za-z0-9]+\.(com|edu|net)","website name kept secret"
write-host $newstr

The first parameter of -replace is the RegEx that describes the pattern you want to find, and the second
parameter is the string you want to replace it with. Think of this switch as being a very powerful search-and-replace feature.

Don't confuse the -replace switch with the string's "replace" method , which performs a literal search and replace. The -replace switch allows you to define regular expressions to describle the matching text that needs to be replace.

29.
$price = 49.998375
write-host [Math]::round($price,2)
If you want to return a value in dollars and cents,so you have to round this value off to contain only two decimal places. you can do this by using the [Math]::round

30.
$array1 = 35,72,23,61,83
$singlevalarray = ,12
$array1 = [array](35,72,23,61,83)

windows powershell treats arrays no differently from collections. A collection in windows powershell is just what the name implies:a collection or grouping of any number of objects. you create a collection by using the @() method,so you can also use this method for creating an array, like this:

$array1 = @(35,72,23,61,83)
$blankarray = @()

write-host $array1[3]
write-host $array1[7]

$array1 [-1]
access the last item of an array by using the index -1

31. looping through arrays
$names = "steve","bill","jeff","mark","ryan"
for ($i = 0 ; $i -lt $names.length; $i ++)
{
write-host $names[$i]
}
write-host
foreach ($item in $names )
{
write-host $item
}
write-host
for ($i = $str.length - 1; $i -ge 0 ;$i-- )
{
write-host $str[$i]
}

32. Creating multidimensional arrays
$array1 = (1,2,3),(4,5,6),(7,8,9)
write-host $array1[1][2]

33.
$processes = @()
foreach ($proc in get-process)
{
$processes += $proc
}
write-host ("number of items: " + $processes.length)
for ($i = 0; $i -lt $processes.lentgh; $i++)
{
write-host $process[$i].name
}

34. creating and using hash tables
$userpwdhash = @{jimmy = "n3utron"; optimus = "Pr!m" ;pinky = "8rnn"; bob = "b1l" }
write-host ("pinky's passwd: " + $userpwhash["pinky]")
write-host $userpwdhash.pinky
$userpwdhash

35. Modifying hash tables
$userpwdhash.add ("tony","s7@#")
$userpwdhash.remove("pinky")

36. Looping through hash tables
$names = @($userpwdhash.keys)
foreach ($name in $names)
{
write-host ($name + "=" +$userpwdhash[$name])
}

37.
Set-location c:\windows
MD c:\temp
or
MKDIR c:\temp

remove-item c:\temp
if you are sure that you want to get rid of that directory (including all subdirectories), you can use
remove-item -recurse c:\temp

copy-item c:\temp c:\temp2
move-item c:\temp e:\temp

rename-item e:\temp e:\temp.bak
move-item e:\temp e:\temp.bak

38.
$data = get-content c:\windows\setuplog.txt

$computernames = get-content c:\temp\computers.txt
foreach ($name in $computernames)
{
$compinfo = get-wmiobject -class win32_computersystem -computername $name
write-host ($compinfo.name + "-" + $compinfo.manufacturer + "-" + $compinfo.model)
}

39.
get-childitem c:\windows\system32 > c:\tmp\system32_contents.txt
get-childitem c:\windows\system32 | out-file c:\tmp\system32_contents1.txt

get-chileitem c:\windows\system32 | out-file c:\test.txt -encoding ASCII
-encoding: Unicode,UTF7,UTF8,UTF32,ASCII,Default,OEM

-append appends to the file rather than overwriting its contents

-width defines the maximum number of characters on each line.

-force tries to overcome any restrictions for writing to the output file,such as overriding the read-only attribute of the file.

-noclobber prevents out-file from trying to write to the output file if it already exists.

-confirm prompts for confirmation before continuing with the command.

get-childitem c:\windows | set-content c:\tmp\test.txt

set-content is same as out-file, but set-content doesn't have an append switch like out-file. because set-content can't append to a file; you have to use the add-content cmdlet instead.

40.
<animal type="camel">joe</animal>
animal is a element tag in xml file
type is a attribute
camel is the value of type
joe is the data

[xml]$myxmlfile = get-content c:\tmp\sample.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<desert name="sahara">
<animal type="camel">joe</animal>
<animal type="snake">mark</animal>
<animal type="elephant">allan</animal>
</desert>

$myxmlfile.desert.name
$myxmlfile.desert.animal

$newanimal = $myxmlfile.createelement("animal")
$newanimal.setattribute("type","vulture")
$newanimal.psbase.innertext = "george"
$myxmlfile.desert.appendchild($newanimal)

get-process | export-clixml c:\tmp\process.xml
$prochistory = import-clixml c:\tmp\process.xml
$prochistory

$prochistory | where-object {$_.handles -gt 100 } | sort-object handles

41. working with html

get-process | convertto-html | out-file c:\tmp\processes.html

$format = "<title>my processes </title>"
$format += "<style>"
$format += "table{border-width:2px;border-style:solid;background-color;yellow}"
$format += "TH{color:blue}"
$format += "td{color:red}"
$format += "</style>"

$body = "<center><h1>process list</h1></center>"

get-process | convertto-html -head $format -body $body | out-file c:\tmp\processes.html

42.
get-date -displayhint date
get-date -displayhint time

get-date -format yyyymmdd
get-date -uformat %y%m%d

$date1 = get-date -year 1983 -month 2 -day 3
$date2 = get-date -year 2008 -month 7 -day 14
$diff = $date2 - $date1

43.
$startdate = get-date "4/11/2014 3:20am"
write-host ("task runs on :")
write-host $startdate
for ($i = 15;$i -le 60;$i +=15)
{
write-host $startdate.adddays($i)
}

All the other add methods have very intuitive names:
Add(adds a timespan value)
AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds
AddTicks
AddYears

$now = get-date
$now.addhours(-8723)

$date1 = get-date "1/3/2014"
$date2 = get-date "4/2/2014"
$date1.isdaylightsavingtime
$date2.isdaylightsavingtime

44.using the timezone class
$tz = [timezone]::currenttimezone
$d = get-date
$tz.getutcoffset($d).hours

45.Defining function
function getosinfo($computername)
{
$osinfo = get-wmiobject win32_operatingsystem -computer $computername
write-host ($osinfo.caption + " " + $osinfo.version + " service pack" + $osinfo.servicepackMajorversion + "." +$osinfo.servicepackminorversion)
}

getosinfo mail01

46.
function dirwin
{
return get-childitem $env:windir
}

function dirwinnames
{
$dir = get-childitem $env:windir
foreach($item in $dir)
{
write-output $item.name
}
}

47.
function changename
{
$name = "lala"
}
$name = "0000"
write-output $name
changename
write-output $name

in this script, have same output. $name value doesn't change.

function changename2
{
$script:name = "lala-99"
}
$name = "0000-99"
write-host $name
changename2
write-host $name

by use $script:name to change value is the correct way.

48.
#REQUIRES -Version 2.0
function Write-Yellow
{
<#
.Synopsis
write some text in yellow foreground color
.Description
this function displays the text you provide
.Parameter out
string to display
.Example
ps> write-yellow "show this in yellow"
.link
about_functions
.notes
author:lala
#>
[CmdleBinding()]
param
(
[parameter(mandatory=$true,valuefrompipeline=$true)]
[alias("out")]
[string]$outstring
)

begin
{
write-host "hello,up"
}

process
{
write-host $outstring
}

end
{
write-host "bye"
}
}

<#
.......
#>
is a feature called Autohelp, if you run get-help against this script, the autohelp feature displays.

49.
Start-job -scriptblock { "get-childitem c:\"}
$myjob = start-job -scriptblock {"get-childitem c:\"}
receive-job -job $myjob

receive-job -ID 5 -keep

receive-job -ID 3

wait-job $myjob -timeout 60

wait-job $myjob -timeout 60
if ($myjob.jobstateinfo.state -ne "completed")
{
write-host "job timed out!"
}
else
{
$data = receive-job $myjob
}

50.speaking powershell with a different computer,
essential components:
.net framework 2.0
powershell 2
winrm 2.0 service

command:
enter-pssession computer1 -credential mydomain\admin

PS U:\> winrm quickconfig
WinRM already is set up to receive requests on this machine.
WinRM is not set up to allow remote access to this machine for management.
The following changes must be made:

Create a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this machine.
Enable the WinRM firewall exception.

51.
invoke-command -computername corpdc1 -scriptblock {get-date}

with "scriptblock", to tell invoke-command which command or set of commands you want to run on
the remote host.

$s = new-pssession -computername pc001
invoke-command -session $s -scriptblock {$start = get-date}
invoke-command -session $s -scriptblock {(get-date) - $start}
remove-pssession $s

invoke-command -computername computer1,computer2 -scriptblock {get-childitem c:\} -asjob
-asjob switch runs that command on the specified computer,but the job object itself is stored on
the local computer.

52.
Set-PSBreakpoint -script myscript.ps1 -command "get-wmiobject"

53.AD opertation

script 1: connecting to Active Directory

$objadsi = [adsi]""
$domain = $objadsi.distinguishedname
$usercontainer = [adsi]("LDAP://cn=users," + $domain )
foreach($child in $usercontainer)
{
write-host $child.samaccountname
}

Script 2: Querying for objects and attributes

$objadsi = [adsi]""
$domain = $objadsi.distinguishedname
$objdomain = [adsi]("LDAP://" + $domain)
$search = new-object System.DirectoryServices.DirectorySearcher
$search.SearchRoot = $objDomain
$search.Filter = "(&(objectClass=user)(giveName=*)(sn=*))"
$search.SearchScope = "Subtree"
$results = $search.FindAll()
foreach($item in $results)
{
$objUser = $item.GetDirectoryEntry()
write-host ($objuser.displayname)
}

Script 3: Dynamically obtaining a user's distinguishedName

function GetUserDN([string]$username)
{
$objADSI = [adsi]""
$domain = $objADSI.distinguishedname
$objDomain = [adsi](*LDAP://" + $domain)
$search = New-Object System.DirectoryServices.DirectorySearcher
$search.SearchRoot = $objDomain
$search.Filter = "(sAMAccoutName=$username)"
$search.SearchScope = "Subtree"
$result = $search.FindOne()
if ($result -eq $null)
{
return $null
}
else {
return $result.GetDirectoryEntry().distinguishedName
}
}

$username = "administrator"
$userDN = GetUserDN($username)
if ($userDN -eq $null)
{
write-host ("Unable to find" + $username)
}
else {
write-host ($username + " - " + $userDN)
}

Script 4: Modifying object Attributes

$user = [adsi]"LDAP://CN=testuser,ou=test,dc=testlab,dc=local"
$user.put("givenName","Chris")
$user.put("sn","Laile")
$user.put("displayName","Laile,Chirs")
$user.put("description","Master of Disaster")
$user.SetInfo()

Script 5: Updating Group Membership

$user = "cn=testuser,ou=test,dc=testdom,dc=local"
$group = [ADSI] "LDAP://cn=Mygroup,cn=users,dc=testdom,dc=local"
$group.add("LDAP://" + $user)
$group.SetInfo()

Script 6: Getting to the Raw ADSI object Using psbase
$ou = [adsi]"LDAP://cn=users,dc=testlab,dc=local"
$ou.psbase.children

54.Using conditional statements

set a=2
if %a% EQU 2 (
Echo the value is two!
) else (
Echo the value is not two!
)

EQU -eq Equal
NEQ -ne Not equal
LSS -lt Less than
LEQ -le Less than or equal
GTR -gt Greater than
GEQ -ge Greater than or equal

55.
$data = get-content computers.txt
foreach($line in $data)
{
$pingresult = get-wmiobject -query "select * from win32_pingstatus where address='$line'"
if ($pingresult.statuscode -eq 0 )
{
copy-item processed.txt \\$line\c$
}
}

56.
$header = "username","lastname","firstname"
$contents = Import-CSV uses.txt -header $header
foreach($user in $contents)
{
write-host $user.firstname $user.lastname
}

本文出自 “想?不想!” 博客,谢绝转载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: