6.##################################################################################################Querying WMI
Get-WmiObject win32_bios
Get-WmiObject win32_computersystem
Get-WmiObject win32_computersystem | Format-List name,model, manufacturer
Get-WmiObject win32_computersystem | Format-List *
Get-WmiObject win32_computersystem | Format-List [a-z]*
Get-WmiObject win32_computersystem | Format-List D*
Get-WmiObject win32_computersystem | Format-List d*,t*
Get-Alias | where {$_.definition -eq 'Get-WmiObject'}
gwmi win32_logicaldisk
gwmi win32_logicaldisk -filter drivetype=3
objDiskobjDisk=Get-WmiObject win32_logicaldisk -filter drivetype=3
objDisk=Get−WmiObjectwin32logicaldisk−filterdrivetype=3|Measure−Object−propertyfreespace−Minimum−MaximumobjDisk
objDisk=Get−WmiObjectwin32logicaldisk−filterdrivetype=3|Measure−Object−propertyfreespace−Minimum−Maximum|Select−Object−Propertyproperty,maximum,minimumobjDisk=Get-WmiObject win32_logicaldisk -filter drivetype=3 |
Measure-Object -property freespace -Minimum -Maximum |
Select-Object -Property property, maximum, minimum |
Format-Table -autosize
strComputer="."wmiNS = "root/cimv2"
$wmiQuery = "Select * from win32_share"
objWMIServices=Get−WmiObject−computerstrComputer -namespace wmiNS‘−querywmiQuery
$objWMIServices | Format-List *
Win32_Share Properties
Data Type
Property
Meaning
Boolean
AllowMaximum
Allow maximum number of connections? True or false
string
Caption
Short, one-line description
string
Description
Description
datetime
InstallDate
When the share was created (optional)
uint32
MaximumAllowed
Number of concurrent connections allowed Only valid when AllowMaximum is set to false
string
Name
Share name
string
Path
Physical path to the share
string
Status
Current status of the share: degraded, OK, or failed
uint32
Type
Type of resource shared: disk, file, printer, etc.
strComputer="."wmiNS = "root/cimv2"
wmiQuery="Selectnamefromwin32Share"objWMIServices = Get-WmiObject -computer strComputer−namespacewmiNS `
-query wmiQueryobjWMIServices | Sort-Object -property name | Format-List -property name
strComputer="."wmiNS = "root/cimv2"
wmiQuery="Selectname,path,AllowMaximumfromwin32share"objWMIServices = Get-WmiObject -computer strComputer−namespacewmiNS `
-query wmiQueryobjWMIServices | Sort-Object -property name |
Format-List -property name,path,allowmaximum
Get-Process
Get-Process -name explorer
Get-WmiObject win32_process |more
Get-WmiObject win32_process -Filter "name='explorer.exe'"
Get-WmiObject win32_process -Filter "name='explorer.exe'" |
Format-Table handlecount,quotaNonPagedPoolUsage, PeakVirtualSize,
WorkingSetSize, VirtualSize, UserModeTime,KernelModeTime,
ProcessID, Name
gwmi win32_logicaldisk >c:/mytest/DiskInfo.txt
gwmi win32_operatingsystem >c:/mytest/OSinfo.txt
gwmi win32_ComputerSystem >>c:/mytest/OSinfo.txt; `
notepad c:/mytest/OSinfo.txt
strComputer="."wmiNS = "root/cimv2"
wmiQuery="Select∗fromwin32sharewherename=′c'"
objWMIServices=Get−WmiObject−computerstrComputer -namespace wmiNS−querywmiQuery
$objWMIServices | Format-List *
strComputer="."wmiClass = "win32_Share"
wmiFilter="name=′c'"
objWMIServices=Get−WmiObject−computerstrComputer `
-class wmiClass−filterwmiFilter
$objWMIServices | Format-List *
strComputer="."wmiNS = "root/cimv2"
wmiQuery="Selectnamefromwin32Sharewherename>′d′"objWMIServices = Get-WmiObject -computer strComputer‘−namespacewmiNS -query wmiQueryobjWMIServices | Sort-Object -property name |
Format-List -property name
strComputer="."wmiNS = "root/cimv2"
wmiQuery="SelectstartName,namefromwin32service"objWMIServices = Get-WmiObject -computer strComputer‘−namespacewmiNS -query wmiQueryobjWMIServices | Sort-Object startName, name |
Format-List name, startName
strFile="c:/mytest/ServiceAccounts.txt"New−Variable−nameconstASCII−value"ASCII"‘−optionconstantFormat−Listname,startName|Out−File−filepathstrFile -encoding $constASCII `
-append -noClobber
strComputer="."wmiNS = "root/cimv2"
strWhere="′ipc'"
wmiQuery="Select∗fromwin32Sharewherename="+strWhere
"Properties of Share named: " + strWhereobjWMIServices = Get-WmiObject -computer strComputer‘−namespacewmiNS -query wmiQueryobjWMIServices |
Format-List -property [a-z]*
strComputer="."wmiNS = "root/cimv2"
wminQuery="Select∗fromwin32product"Write−Host"CountingInstalledProducts.This"‘"maytakealittlewhile."−foregroundColorblue‘nobjWMIServices = Get-WmiObject -computer strComputer‘−namespacewmiNS -query wmiQueryfor(i=1; i−leobjWMIServices.count;i++)Write−Host"//"−noNewLine−foregroundColorredWrite−Host‘n‘n"Thereare"objWMIServices.count `
" products installed."
dteStart=Get−DatedteEnd = Get-Date
dteDiff=New−TimeSpandteStart dteEndWrite−Host"Ittook"dteDiff.totalSeconds " Seconds" `
" for this script to complete"
gwmi win32_environment
gwmi win32_environment | Format-List *
gwmi win32_environment | Format-Table name, variableValue, userName
gwmi win32_environment | Format-Table name, variableValue
gwmi win32_environment | Format-Table name, variableValue -AutoSize
Set-Location env:
Get-ChildItem
Set-Location c:/
Get-Alias | where {_.definition -eq "Get-History"} Get-Alias | where {_.definition -eq "Invoke-History"}
ghy
sl env:;gci
sl c:/
sl env:;gci;sl c:/
gwmi win32_environment | Format-Table name, variableValue -AutoSize
Ihy 169
7.##################################################################################################Working with Active Directory
ADSI-Supported Providers
Provider
Purpose
WinNT
To communicate with Windows NT 4.0 Primary Domain Controllers (PDCs) and Backup Domain Controllers (BDCs), and with local account databases for Windows 2000 and newer workstations and servers
LDAP
To communicate with LDAP servers, including an Exchange 5.x directory and Windows 2000 Server or Windows Server 2003 Active Directory
NDS
To communicate with Novell Directory Services servers
NWCOMPAT
To communicate with Novell NetWare 3.x servers
strCLass="organizationalUnit"StrOUName = "ou=MyTestOU"
$objADSI = [ADSI]"LDAP://dc=nwtraders,dc=msft"
objOU=objADSI.create(strCLass,StrOUName)
$objOU.setInfo()
Common Relative Distinguished Name Attribute Types
Attribute
Description
DC
Domain Component
CN
Common Name
OU
Organizational Unit
O
Organization Name
Street
Street Address
C
Country Name
UID
User ID
Accelerator
Variable
Provider
ADsPath
[ADSI]
$objDomain
LDAP://
OU=hr, dc=a, dc=com
a = New-Object foo #creates an errorerror.count
error[0].CategoryInfoerror[0].ErrorDetails
error[0].Exceptionerror[0].FullyQualifiedErrorId
error[0].InvocationInfoerror[0].TargetObject
b=New−Objectbarfor(i = 0 ; error.count;i++)
{error[i].CategoryInfo
error[i].ErrorDetails
error[i].Exception
error[i].FullyQualifiedErrorId
error[i].InvocationInfo
error[i].TargetObject}
erroractionpreference="SilentlyContinue""Therearecurrently"+error.count + "errors"
Error.clear() #b = New-Object bar
if (error.count -eq 1) {"There is currently 1 error"} else {"There are currently " +error.count + "errors"}
erroractionpreference="SilentlyContinue"error.clear()
if (error.count−ne0)"Anerroroccurredduringtheoperation.Detailsfollow:"$error[0].categoryInfo$error[0].invocationinfo$error[0].tostring()StrOUName = "ou=MyTestOU1"
strCLass="User"StrName = "CN=MyNewUser"
$objADSI = [ADSI]"LDAP://ou=myTestOU,dc=nwtraders,dc=msft"
objUser=objADSI.create(strCLass,StrName)
objUser.Put("sAMAccountName","MyNewUser")objUser.setInfo()
intGroupType=2strGroup = "Group"
objGroup=objADSI.create(strCLass,StrName)
objGroup.setInfo()ObjGroup.put("GroupType",$intGroupType)
strCLass="computer"StrName = "CN=MyComputer"
objComputer=objADSI.create(strCLass,StrName)
objComputer.put("sAMAccountName","MyComputer")objComputer.setInfo()
objComputer.put("UserAccountControl",4128)objComputer.setinfo()
User Account Control Values
Ads Constant
Value
ADS_UF_SCRIPT
0X0001
ADS_UF_ACCOUNTDISABLE
0X0002
ADS_UF_HOMEDIR_REQUIRED
0X0008
ADS_UF_LOCKOUT
0X0010
ADS_UF_PASSWD_NOTREQD
0X0020
ADS_UF_PASSWD_CANT_CHANGE
0X0040
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
0X0080
ADS_UF_TEMP_DUPLICATE_ACCOUNT
0X0100
ADS_UF_NORMAL_ACCOUNT
0X0200
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT
0X0800
ADS_UF_WORKSTATION_TRUST_ACCOUNT
0X1000
ADS_UF_SERVER_TRUST_ACCOUNT
0X2000
ADS_UF_DONT_EXPIRE_PASSWD
0X10000
ADS_UF_MNS_LOGON_ACCOUNT
0X20000
ADS_UF_SMARTCARD_REQUIRED
0X40000
ADS_UF_TRUSTED_FOR_DELEGATION
0X80000
ADS_UF_NOT_DELEGATED
0X100000
ADS_UF_USE_DES_KEY_ONLY
0x200000
ADS_UF_DONT_REQUIRE_PREAUTH
0x400000
ADS_UF_PASSWORD_EXPIRED
0x800000
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
0x1000000
$objUser = [ADSI]"LDAP://cn=MyNewUser,ou=myTestOU,dc=nwtraders,dc=msft"
objUser.put("SamaccountName","myNewUser")objUser.put("givenName", "My")
objUser.Put("initials","N.")objUser.Put("sn", "User")
objUser.Put("DisplayName","MyNewUser")objUser.Put("description" , "simple new user")
objUser.Put("physicalDeliveryOfficeName","RQ2")objUser.Put("telephoneNumber", "999-222-1111")
$objUser.Put("mail", "mnu@hotmail.com")
$objUser.Put("wwwHomePage", "http://www.mnu.msn.com")
$objUser.setInfo()
Address Page Mappings
Active Directory Users and Computers Label
Active Directory Attribute Name
Street
streetAddress
P.O. Box
postOfficeBox
City
l (Note that this is lowercase L.)
State/Province
st
Zip/Postal Code
postalCode
Country/Region
c,co,countryCode
$objUser = [ADSI]"LDAP://cn=MyNewUser,ou=myTestOU,dc=nwtraders,dc=msft"
objUser.put("streetAddress","123mainst")objUser.put("postOfficeBox", "po box 12")
objUser.put("l","Bedrock")objUser.put("st", "Arkansas")
objUser.put("postalCode","12345")objUser.put("c", "US")
objUser.put("co","UnitedStates")objUser.put("countryCode", "840")
$objUser.setInfo()
ISO 3166-1 Country Codes
Country Code
Country Name
AF
AFGHANISTAN
AU
AUSTRALIA
EG
EGYPT
LV
LATVIA
ES
SPAIN
US
UNITED STATES
$objUser.put("profilePath", "//London/profiles/myNewUser")
objUser.put("scriptPath","logon.vbs")objUser.put("homeDirectory", "//london/users/myNewUser")
$objUser.put("homeDrive", "H:")
objUser.Put("homePhone","(215)788−4312")objUser.Put("pager", "(215)788-0112")
objUser.Put("mobile","(715)654−2341")objUser.Put("facsimileTelephoneNumber", "(215)788-3456")
objUser.Put("ipPhone","192.168.6.112")objUser.Put("info", "All contact information is confidential," `
+ "and is for official use only.")
aryNames="CN=MyBoss","CN=MyDirect1","CN=MyDirect2"foreach(StrName in aryNames)$objUser=$objADSI.create($strCLass,$StrName)$objUser.setInfo()strDomain = "dc=nwtraders,dc=msft"
strOU="ou=myTestOU"strUser = "cn=MyNewUser"
strManager="cn=myBoss"objUser = [ADSI]"LDAP://strUser,strOU,$strDomain"
objUser.put("title","Mid−LevelManager")objUser.put("department", "sales")
objUser.put("company","NorthWindTraders")objUser.put("manager", "strManager,strou,$strDomain")
objDomain=[ADSI](provider + ou+domain)
objDomain.DeleteoClass, oCn+oUname
$objADSI = [ADSI]"LDAP://ou=myTestOU,dc=nwtraders,dc=msft"
objUser=objADSI.delete(strCLass,StrName)
strCLass = "User"
StrName="CN=MyNewUser"objADSI = [ADSI]"LDAP://ou=myTestOU,dc=nwtraders,dc=msft"
objUser=objADSI.delete(strCLass,StrName)
aryText=Get−Content−Path"c:/labs/ch7/stepbystep.txt"forEach(aryElement in aryText) {strCLass = "organizationalUnit"
StrOUName=aryElement
$objADSI = [ADSI]"LDAP://dc=nwtraders,dc=msft"
objOU=objADSI.create(strCLass,StrOUName)
$objOU.setInfo()
}
aryText=Get−Content−Path"c:/labs/ch7/OneStepFurther.txt"strCLass = "User"
intUsers=9strName = "cn=tempUser"
$objADSI = [ADSI]"LDAP://ou=myTestOU,dc=nwtraders,dc=msft"
for (i=1;i -le intUsers;i++)
{
}
objUser=objADSI.create(strCLass,StrName+i)objUser.setInfo()
objUser.put("streetAddress",aryText[0])
objUser.put("postOfficeBox",aryText[1])
objUser.put("l",aryText[2])
objUser.put("st",aryText[3])
objUser.put("postalCode",aryText[4])
objUser.put("c",aryText[5])
objUser.put("co",aryText[6])
objUser.put("countryCode",aryText[7])
objUser.Put("facsimileTelephoneNumber",aryText[8])
objUser.Put("info",aryText[9])
$objUser.setInfo()
objUser.setInfo()objUser.put("streetAddress", aryText[0])objUser.put("postOfficeBox", aryText[1])objUser.put("l", aryText[2])objUser.put("st", aryText[3])objUser.put("postalCode" , aryText[4])objUser.put("c", aryText[5])objUser.put("co", aryText[6])objUser.put("countryCode", aryText[7])objUser.Put("facsimileTelephoneNumber", aryText[8])objUser.Put("info", aryText[9])objUser.setInfo()
objUser=objADSI.Delete(strCLass,StrName+$i)