Get-ChildItem c:/fso | Where-Object {_.Length -gt 1000} | Sort-Object -Property name foreach (_.Length -gt 1000} | Sort-Object -Property name foreach (i in args) {Get-ChildItemargs) {Get-ChildItemi | Where-Object {$_.length -gt 1000} | Sort-Object -property name}
$args = "localhost","loopback","127.0.0.1"
foreach (iinargs)
{strFile="c:/mytest/"+i +"Processes.txt"
Write-Host "Testing" i"pleasewait...";Get−WmiObject−computernamei -class win32_process |
Select-Object name, processID, Priority, ThreadCount, PageFaults, PageFileUsage |
Where-Object {!_.processID -eq 0} | Sort-Object -property name | Format-Table | Out-FilestrFile}
$args = "localhost"
foreach (iinargs)
{Write-Host "Connecting to" i"pleasewait...";Get−WmiObject−computernamei -class win32_UserAccount |
Select-Object Name, Disabled, PasswordRequired, SID, SIDType |
Where-Object {$_.PasswordRequired -eq 0} |
Sort-Object -property name | Write-Host}
Get-ExecutionPolicy
Set-ExecutionPolicy unrestricted
###RetrieveAndSortServiceState.ps1
$args = "localhost","loopback"
foreach (iinargs)
{Write-Host "Testing" i"..."Get−WmiObject−computerargs -class win32_service |
Select-Object -property name, state, startmode, startname |
Sort-Object -property startmode, state, name |
Format-Table *}
Open the Run dialog box (Start | Run, or the Windows Flag key + R, or Ctrl + Esc then R).
Powershell -noexit C:/mytest/RetrieveAndSortServiceState.ps1
ContainsthefirsttokenofthelastlineinputintotheshellContainsthelasttokenofthelastlineinputintotheshell_
The current pipeline object; used in script blocks, filters, Where-Object, ForEach-Object, and Switch
?Containsthesuccess/failstatusofthelaststatementArgs
Used in creating functions requiring parameters
ErrorIfanerroroccurred,theerrorobjectissavedintheerror variable.
ExecutionContextTheexecutionobjectsavailabletocmdletsforeach
Refers to the enumerator in a foreach loop
HOMETheuser′shomedirectory;settoInput
Input is piped to a function or code block.
MatchAhashtableconsistingofitemsfoundbythe−matchoperatorMyInvocation
Information about the currently executing script or command-line
PSHomeThedirectorywherePSisinstalledHost
Information about the currently executing host
LastExitCodeTheexitcodeofthelastnativeapplicationtoruntrue
Boolean TRUE
falseBooleanFALSEnull
A null object
thisIntheTypes.ps1xmlfileandsomescriptblockinstances,thisrepresentsthecurrentobjectOFS
Output Field Separator used when converting an array to a string
ShellIDTheidentifierfortheshell.ThisvalueisusedbytheshelltodeterminetheExecutionPolicyandwhatprofilesarerunatStartupStackTrace
Contains detailed stack trace information about the last error
strUserPathPathtoregistrysubkey"Software/Microsoft/Windows/CurrentVersion/Explorer"strUserName
Registry value "Logon User Name"
strPathPathtoregistrysubkey"/VolatileEnvironment"strName
An array of Registry values: "LOGONSERVER", "HOMEPATH", "APPDATA", "HOMEDRIVE"
iHoldsasingleregistryvaluenamefromthestrName array of registry values; igetsassignedthevaluebyusingtheForEachalias.strUserPath = "/Software/Microsoft/Windows/CurrentVersion/" `
+ "Explorer"
strUserName="LogonUserName"strPath = "/Volatile Environment"
$strName = "LOGONSERVER","HOMEPATH", "APPDATA","HOMEDRIVE"
Set-Location HKCU:/
Get-ItemProperty -path strUserPath−namestrUserName |
Format-List strUserNameforeach(i in strName) {Get-ItemProperty -pathstrPath -name i|Format−Listi}
a="thisisthebeginning"b = 22
c=a + bc
c=a + bc
b="thisisanumber"c = a+b
c[int]b = 5
c=a + bc
b = "this is a string" #Cannot convert value "this is a number" to type "System.Int32". #Error: "Input string was not in a correct format." #At line:1 char:3 #+b <<<< = "this is a string"
Data Type Aliases
Open table as spreadsheet Alias
Type
[int]
32-bit signed integer
[long]
64-bit signed integer
[string]
Fixed-length string of Unicode characters
[char]
A Unicode 16-bit character
[bool]
True/false value
[byte]
An 8-bit unsigned integer
[double]
Double-precision 64-bit floating point number
[decimal]
An 128-bit decimal value
[single]
Single-precision 32-bit floating point number
[array]
An array of values
[xml]
Xml objects
[hashtable]
A hashtable object (similar to a dictionary object)
$aryComputers = "loopback", "localhost"
Set-Variable -name intDriveType -value 3 -option constant
foreach (strComputerinaryComputers)
{"Hard drives on: " + strComputerGet−WmiObject−classwin32logicaldisk−computernamestrComputer|
Where {.drivetype−eqintDriveType}}
Get-Process |
ForEach-Object `
{if (.cpu−lt100)Write−Host$.name,$.cpu−foregroundcolorblueelseif(_.cpu -gt 100)
{Write-Host .name,_.cpu -foregroundcolor red}}
Get-Service
ForEach-Object
ForEach-Object `
if (.Status−eq"stopped")Write−Host$.name,$.Status−foregroundcolorred−separator",‘n‘t"elseif(_.Status -eq "running")
{Write-Host .name,_.Status -foregroundcolor green -separator ",`n`t"}}
for (a=1;a -le 3 ; $a++) {"hello"}
[int]intPing=10[string]intNetwork = "127.0.0."
for (i=1;i -le intPing;i++)
{
strQuery="select∗fromwin32pingstatuswhereaddress=′"+intNetwork + i+"′"wmi = get-wmiobject -query strQuery"PingingintNetworki..."if(wmi.statuscode -eq 0)
{"success"}
else
{"error: " + $wmi.statuscode + " occurred"}
}
$dtmTime = get-date -h 04 -mi 23 -s 00
do {dtmCurrent=Get−Date−DisplayHinttime"Thecurrenttimeis"+dtmCurrent
"counting to " + dtmtime start-sleep -s 2 } while (dtmCurrent -lt $dtmTime)
"time reached à"
Comparison Operators
Open table as spreadsheet Operator
Description
-eq
equals
-ne
not equal
-gt
greater than
-ge
greater than or equal to
-lt
less than
-le
less than or equal to
-like
wild card comparison
-notlike
wild card comparison
-match
regular expression comparison
-notmatch
regular expression comparison
i=10;do$i−−;"iis$i"until(i -eq 0)
strTxtFile="c:/mytest/loopbackprocesses.txt"i = 0
mytext=Get−ContentstrTxtFile
do {
mytext[i]
i ++ } until (i -eq $mytext.length)
i=0;do$i++;"iisequalto$i"until(i -eq 0)
i=0;do$i++;"iisequalto$i"until(i -eq 0)
i=0;do$i++;"iisequalto$i"while(i -eq 0)
WIN32_Processor Processor Values
0
x86
1
MIPS
2
Alpha
3
PowerPC
6
Intel Itanium
9
x64
wmi=get−wmiObjectwin32processorif(wmi.Architecture -eq 0)
{"This is an x86 computer"}
elseif(wmi.architecture−eq1)"ThisisanMIPScomputer"elseif(wmi.architecture -eq 2)
{"This is an Alapha computer"}
elseif(wmi.architecture−eq3)"ThisisanPowerPCcomputer"elseif(wmi.architecture -eq 6)
{"This is an IPF computer"}
elseif(wmi.architecture−eq9)"Thisisanx64computer"else$wmi.architecture+"isnotacputypeIamfamiliarwith""Currentclockspeedis:"+wmi.CurrentClockSpeed + " MHZ"
"Max clockspeed is : " + wmi.MaxClockSpeed+"MHZ""Currentloadpercentageis:"+wmi.LoadPercentage + " Percent"
"The L2 cache size is: " + $wmi.L2CacheSize + " KB"
a=5;switch(a) { 4{"four detected"} 5{"five detected"} }
wmi=get−wmiobjectwin32computersystem"computer"+wmi.name + " is: "
switch ($wmi.domainrole)
{
0 {"`t Stand alone workstation"}
1 {"`t Member workstation"}
2 {"`t Stand alone server"}
3 {"`t Member server"}
4 {"`t Back up domain controller"}
5 {"`t Primary domain controller"}
default {"`t The role can not be determined"}
}
intFolders=10intPad
i=1New−Variable−NamestrPrefix−Value"testFolder"−Optionconstantdoif($i−lt10)$intPad=0new−item−pathc:/mytest−name$strPrefix$intPad$i−typedirectoryelsenew−item−pathc:/mytest−name$strPrefix$i−typedirectory$i++until(i -eq $intFolders+1)
{intPad=0remove−item−pathc:/mytest−namestrPrefixintPadi -type directory}
else
{remove-item -path c:/mytest -name strPrefixi -type directory}
{intPad=0remove−item−pathc:/mytest/strPrefixintPadi -type directory}
else
{remove-item -path c:/mytest/strPrefixi -type directory}
{intPad=0Remove−item−pathc:/mytest/strPrefixintPadi}
else
{Remove-item -path c:/mytest/strPrefixi}
wmi = Get-WmiObject -class __Namespace -namespace root "Listing namespaces on " +wmi[0].__server +
" please wait a second "
for (i=0;i -le wmi.length;i++)
{if (i−ltwmi.length)
{Write-Host -noNewLine "."
Start-Sleep -m 75}
else
{Write-Host "."}
}
wmi|Format−ListnameWrite−Host−foregroundColorgreen"Thereare"wmi.length `
"namespaces on this machine `n"
wmiNS = "root/cimV2" Get-WmiObject -class __Provider -namespacewmiNS |
Sort-Object -property Name |
Format-List name
Variable Name
Variable Use
strComputerNameofcomputertorunthescriptonwmiNS
WMI namespace containing WMI class used in the script
strUsrUsernameforconnectiontoremotecomputerstrPWD
Password of user connecting to remote machine
strLoclLanguagetobeusedwithWMIconnectionstrAuth
Credential authority, for example, Kerberos, NTLM
iFlagSecurityflag;usedtospecifytimeoutvaluestrComputer = "."
wmiNS="/root/cimv2"strUsr ="" #Blank for current security. Domain/Username
strPWD = "" #Blank for current security.strLocl = "MS_409" #US English. Can leave blank for current language
strAuth = "" #if specify domain in strUsr this must be blankiFlag = "0" #only two values allowed: 0 and 128.
objLocator=New−Object−comobject"WbemScripting.SWbemLocator"objWMIService = objLocator.ConnectServer(strComputer,
wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)
colItems=objWMIService.subClassesOf()
Write-Host "There are: " colItems.count"classesinwmiNS"
foreach (objItemIncolItems)
{
$objItem.path_.class
}
strComputer="."wmiNS = "/root/cimv2"
strUsr ="" #Blank for current security. Domain/UsernamestrPWD = "" #Blank for current security.
strLocl = "MS_409" #US English. Can leave blank for current languagestrAuth = "" #if specify domain in strUsr this must be blank
$iFlag = "0" #only two values allowed: 0 and 128.
objLocator = New-Object -comobject "WbemScripting.SWbemLocator" #objWMIService = objLocator.ConnectServer(strComputer, `
# wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)
#
# colItems=objWMIService.subClassesOf()
# Write-Host "There are: " colItems.count"classesinwmiNS"
# foreach (objItemIncolItems)
# {
# $objItem.path_.class
# }
objLocator|Get−MemberobjWMIService = objLocator.ConnectServer(strComputer, `
wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)
objWMIService|Get−MembercolItems = objWMIService.subClassesOf()colItems | Get-Member
wmiClass="WIN32Service"objLocator = New-Object -comobject "WbemScripting.SWbemLocator"
#objLocator|Get−MemberobjWMIService = objLocator.ConnectServer(strComputer,
wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)
#objWMIService|Get−MemberobjItem = objWMIService.Get(wmiClass)
$objItem | Get-Member
wmiQuery="Select∗fromWin32Desktop"wmiNS = "root/cimv2"
strComputer="."objWMIService = Get-WmiObject -computer strComputer−namespacewmiNS -query wmiQueryobjWMIService | Format-List *
objWMIService|Format−List−propertynameobjWMIService | Format-List -property name, screensaverexecutable
objWMIService|Format−List−propertyname,screensaverexecutable,screensaverSecureobjWMIService | Format-List -property name, screen*
Get-Service
Get-Service |sort -property status
Get-Service |sort -property name
Get-Service |sort status, name
Get-Service | where {_.DisplayName -match "server"} Get-Service | where {$_.name -eq "alerter"}a=Get-Service | where {_.name -eq "alerter"}a | gm
a.statusStop−Service−InputObjecta
Start-Service -InputObject aa.status
wmiQuery="Select∗fromwin32Printer"objWMIServices | Format-List name
objWMIServices|Format−Listname,portnameobjWMIServices | Format-List name, portname, capabilitydescriptions
$objWMIServices | GM