Connect to WMI
WMI stands for Windows Management Instrumentation (WMI).
It is important to realize there are default values utilized for the WMI connection.
The default values are stored in the following registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Scripting. There are two keys: DEFAULT IMPERSONATION LEVEL and DEFAULT NAMESPACE. DEFAULT IMPERSONATION LEVEL is set to a value of 3, which means that WMI impersonates the logged-on user and therefore uses the logged-on user name, credentials, and rights. The default namespace is Root\cimv2.
Use the Get-ItemProperty cmdlet to verify the default WMI configuration on a local computer:
get-itemproperty HKLM:\SOFTWARE\Microsoft\WBEM\Scripting
Retrieving properties
1. Only show the properties name, model, manufacturer:
Get-WmiObject WIN32_computersystem | Format-list name, model,manufacturer
2. Show all the properties:
Get-WmiObject WIN32_computersystem | Format-list *
3. Show properties begin with the letters a through z:
Get-WmiObject WIN32_computersystem | Format-List [a-z]*
4. List properties that begin with the letter d.
Get-WmiObject WIN32_computersystem | Format-List D*
5. To list all the properties and their values that begin with either the letter d or the letter t
Get-WmiObject WIN32_computersystem | Format-List d*,t*
Work with Disk drives
To retrieve the default properties for each drive on the system:
gwmi win32_logicaldisk
- Local disk drives: -filter drivetype=3
gwmi win32_logicaldisk -filter drivetype=3
The WIN32_LogicalDisk WMI class property DriveType can have a value of 0 to 6 (inclusive). The most useful of these values are as follows: 3 (local disk), 4 (network drive), 5 (compact disk), and 6 (RAM disk).
$LogicalDisks = Get-WMIObject -ComputerName xxxx Win32_LogicalDisk
$LocalHDisks = $LogicalDisks | Where-Object { $_.DriveType -eq 3 }
$LocalHDisks | ft -auto @{Label=”Drive”;`
Expression={$_.DeviceID};
width=5
align=”Right”},`
@{Label=”Volume Label”;`
Expression={$_.VolumeName};
Width=25},`
@{Label=”%Free”;`
Expression={[int]($_.FreeSpace/$_.Size * 100)};`
Width=8},`
@{Label=”GBFree”;`
Expression={$([math]::round(($_.FreeSpace/1gb),0))};`
Width=8},`
@{Label=”Size(GB)”;`
Expression={$([math]::round(($_.Size/1gb),0))};`
Width=8}
Query every property from every instance of a class
To return all information from all instances, perform the following steps:
1. Make a connection to WMI by using the Get-WmiObject cmdlet.
2. Use the -query argument to supply the WQL query to the Get-WmiObject cmdlet.
3. In the query, use the Select statement to choose everything: Select * .
4. In the query, use the From statement to indicate the class from which you wish to retrieve data. For example, From Win32_Share.
E.g. List shared drives:
$strComputer = "." $wmiNS = "root\cimv2" $wmiQuery = "Select * from win32_share" $objWMIServices = Get-WmiObject -computer $strComputer -namespace $wmiNS ` -query $wmiQuery $objWMIServices | Format-List *
Similarly you can also select specific data:
Perform the following steps:
1. Make a connection to WMI by using the Get-WmiObject cmdlet.
2. Use the -query argument to supply the WMI query to the Get-WmiObject cmdlet.
3. In the query, use the Select statement to choose the speci c property you are interested in— for example, Select name.
4. In the query, use the From statement to indicate the class from which you want to retrieve data—for example, From Win32_Share.
$strComputer = "." $wmiNS = "root\cimv2" $wmiQuery = "Select name from win32_Share" $objWMIServices = Get-WmiObject -computer $strComputer -namespace $wmiNS ` -query $wmiQuery $objWMIServices | Sort-Object -property name | Format-List -property name
working with running processes
1. Get-process cmdlet to obtain a list of processes.
2. To return information about the Explorer process, use the -name argument: Get-process -name explorer
3. Get information about processes: Get-wmiobject win32_process | more
4. To retrieve information about the Explorer.exe process, use the -filter argument and specify that the name property is equal to Explorer.exe.
Get-wmiObject win32_process -Filter "name='explorer.exe'"
5. To display a table that is similar to the one produced by Get-Process:
Get-WmiObject win32_process -Filter "name='explorer.exe'" | Format-Table handlecount,quotaNonPagedPoolUsage, PeakVirtualSize, WorkingSetSize, VirtualSize, UserModeTime,KernelModeTime, ProcessID, Name
The – filter argument is surrounded by double quotation marks. The value being supplied for the property is surrounded by single quotes—for example, -Filter “name=’explorer.exe'”. This can cause a lot of frustration if not followed exactly.
Redirect output
There are two ways to redirect output to a file.
You can use redirection arrow > or cmdlet out-file
Use > to redirect output to a file
After the redirection, if you want to open the file, such as Use Notepad to open the file, but include the Get-WmiObject (gwmi) command, separated by a semicolon. This is illustrated next. (I’ve continued the command to the next line using the grave accent character (`) for readability.)
gwmi win32_ComputerSystem >>c:\mytest\OSinfo.txt; ` notepad c:\mytest\OSinfo.txt
Use out-file
we can create a variable $strFile to store the path of the text file.
$strFile=c:\mytest\OSinfo.txt
Then use the out-file to produce an output file containing the results of the previous command. To ensure the output file is easily read, use ASCII encoding by using the -encoding argument.
Out-file -filepath $strFile -encoding ASCII
If you don’t want to overwrite any existing file, use the -append argument only add to the end of the text file, -noClobber argument tells out-file not to overwrite any existing files.
Eliminating the WMI query argument
1. Declare a variable called $strComputer and assign the WMI shortcut dot (.) to it, which means connect to the WMI service on the local computer. $strComputer="."
2. Declare another variable and call it $wmiClass="win32_Share"
3. Declare a variable and call it $wmiFilter, this variable will hold the string that contains the WMI filter to be used with the Get-wmiObject command.
$wmifilter="name='c$'"
4. Then use the Get-WmiObject cmdlet to query all the info:
Get-WmiObject -computer $strComputer -class $wmiclass -filter $wmifilter
Utilizing an operator
greater-than and less-than operators
You can use these two operators in letters: >D means letters D through Z. Also keep in mind that D$ is greater than D.
If you really want shares that begin with the letter E, then you can specify “greater than or equal to E.” This command would look like >=’E’.
Where VS filter
Where clause can be used to limit the specific data returned by a query.
Get-WmiObject -ComputerName "." -Namespace "root\cimv2" -query "Select * from win32_share where name='ipc$'"
You can also use -filter parameter to replace the where clause:
Get-WmiObject -ComputerName "." -Namespace "root\cimv2" -class "win32_share" -filter "name='ipc$'"
Property and “select .., … from”
Get-WmiObject -Query “Select name, handle from win32_process”
or you can use:
Get-WmiObject -Class WIN32_Process -Property name, handle
Use WMI to find installed software
The win32_product WMI class contains the software object in Windows, then use the for statement to print out a progress indicator. To calculate the script executing time, we use New-TimeSpan to calculate the time difference between two time points.
The code to get the number of software is:
$wmiQuery="Select * from win32_product" $dteStart=Get-Date write-host "counting installed products. This"` "may take a little while." -ForegroundColor blue `n $objWMIServices=Get-WmiObject -ComputerName "." -Query $wmiQuery for ($i=1; $i -le $objWMIServices.count;$i++) {write-host "/\" -noNewLine -foregroundColor Red} # -noNewLine make sure write-host write everything in one line without starting a new line. $dteEnd=Get-Date $dteDiff=New-TimeSpan $dteStart $dteEnd write-host `n "there are " $objWMIServices.count ` "products installed. It took" $dteDiff.Seconds "seconds "` "for this script to complete".
Work on system environment
Two ways to get the environment variables:
1. We can use Get-WmiObject cmdlet to view the common properties of the WIN32_Environment WMI class. Most of time, we only need to know the name, variableValue and userName, so we can use Format-table to list the variables nicely. -AutoSize argument can make the space between two columns tidy.
PS C:\Windows\system32> gwmi win32_environment | ft name,variableValue -AutoSize name variableValue ---- ------------- FP_NO_HOST_CHECK NO USERNAME SYSTEM Path %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPow... ComSpec %SystemRoot%\system32\cmd.exe TMP %SystemRoot%\TEMP OS Windows_NT windir %SystemRoot% PROCESSOR_ARCHITECTURE AMD64 TEMP %SystemRoot%\TEMP PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC PSModulePath %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\ NUMBER_OF_PROCESSORS 1 PROCESSOR_LEVEL 6 PROCESSOR_IDENTIFIER Intel64 Family 6 Model 78 Stepping 3, GenuineIntel PROCESSOR_REVISION 4e03 TMP %USERPROFILE%\AppData\Local\Temp TEMP %USERPROFILE%\AppData\Local\Temp
2. We can use the Env PS drive by using set-location cmdlet to set the location to the Env PS drive, then get-childItem to show the variables.
PS C:\Windows\system32> Set-Location env: PS Env:\> Get-ChildItem Name Value ---- ----- ALLUSERSPROFILE C:\ProgramData APPDATA C:\Users\Administrator.WIN-T4NRETS7221\AppData\Roaming CommonProgramFiles C:\Program Files\Common Files CommonProgramFiles(x86) C:\Program Files (x86)\Common Files CommonProgramW6432 C:\Program Files\Common Files COMPUTERNAME TEST ComSpec C:\Windows\system32\cmd.exe FP_NO_HOST_CHECK NO HOMEDRIVE C: HOMEPATH \Users\Administrator.WIN-T4NRETS7221 LOCALAPPDATA C:\Users\Administrator.WIN-T4NRETS7221\AppData\Local LOGONSERVER \\TEST NUMBER_OF_PROCESSORS 1 OS Windows_NT
You can change back to C drive by command sl (set-location): sl c:\
Enable Windows Remote Management
Launch the Group Policy Management Console (GPMC) and navigate to the following path: Computer Policies | Administrative Templates | Windows Components | Windows Remote Management (RM) | WinRM Service. Then, double-click Allow Remote Server Management Through WinRM Policy (Figure A).
Figure A
Select the radio button next to Enabled and place the “*” for each line in the text box next to IPv4 and IPv6. Now click OK to save the settings (Figure B).
Figure B
Note: WinRM will be set to allow connections from any IPv4/IPv6 addresses when using the “*”. However, if you wish to secure access to a specific IP address or IP range, enter that in the textbox instead to lockdown the WinRM environment.
2: Configure Windows Firewall Settings
While still in GPMC, navigate to the following path: Computer Policies |Windows Settings | Security Settings | Windows Firewall with Advanced Security (Figure C).
Figure C
Expand the selection and right-click Incoming Connections, New Rule. The New Inbound Rule Wizard will appear. Select the radio button next to Predefined and from the drop-down menu, select Windows Remote Management. Click Next to continue (Figure D).
Figure D
Two predefined rules will be displayed on this screen (Figure E). Click Next to proceed.
Figure E
Select the Allow The Connection option and click Finish to complete the configuration (Figure F).
Figure F
The two inbound rules should be successfully configured and displayed in GPMC (Figure G).
Figure G
3: Configure Windows Remote Service
The last step in the configuration phase also occurs in GPMC. Navigate to the following path: Computer Policies |Windows Settings | Security Settings | System Services (Figure H).
Figure H
Double-click the Windows Remote Management (WS-Management) service to configure the properties. In the new window that opens, select Automatic under Select Service Startup Mode and check the Define This Policy Setting option (Figure I).
Figure I
Navigate to the following path: Computer Policies | Preferences | Control Panel Settings | Services. Right-click it and select New | Service (Figure J). Under the General Tab, select No Change from the drop-down menu next to Startup. Enter WinRM in the text box next to the Service Name and select Start Service from the drop-down menu next to Service action (Figure K).
Figure J
Figure K
Under the Recovery Tab, select Restart The Service from the drop-down menu next to the First, Second, and Subsequent Failures sections, then click OK to save the settings changes.