Wmi Cookbook PDF
Wmi Cookbook PDF
PowerShell
Credentials
You can also use Select-String to find interesting WMI classes. This will find all WMI classes related to Print:
Methods
------{SetPowerState,
{SetPowerState,
{SetPowerState,
{SetPowerState,
{}
R...
R...
R...
R...
Properties
---------{Access, Availabilit...
{Access, Availabilit...
{Access, Availabilit...
{Availability, Bytes...
{DiskSpaceUsed, Limi...
Simply replace the search word in $Keyword with whatever you are looking for. And then, when you know the WMI class name, submit it to
Get-WmiObject and omit the -List parameter to get the actual results:
Get-WmiObject -Class Win32_DiskPartition
CIM_DataFile
Msft_CliAlias
Win32_BaseBoard
Win32_BIOS
Author Bio
Tobias Weltner is a long-term Microsoft PowerShell MVP, located in Germany. Weltner offers entry-level and advanced PowerShell
classes throughout Europe, targeting mid- to large-sized enterprises. He just organized the first German PowerShell Community
conference which was a great success and will be repeated next year (more on www.pscommunity.de).. His latest 950-page
PowerShell 3.0 Workshop was recently released by Microsoft Press.
To find out more about public and in-house training, get in touch with him at [email protected].
Win32_BootConfiguration
WIN32_CACHEMEMORY
Win32_CDROMDrive
Win32_ComputerSystem
Win32_ComputerSystemProduct
WIN32_DCOMApplication
WIN32_DESKTOP
WIN32_DESKTOPMONITOR
Win32_DeviceMemoryAddress
Win32_Directory
Win32_DiskDrive
Win32_DiskPartition
Win32_DiskQuota
Win32_DMAChannel
Win32_Environment
Win32_Group
Win32_IDEController
Win32_IRQResource
Win32_LoadOrderGroup
Win32_LogicalDisk
Win32_LogicalMemoryConfiguration
Win32_LogonSession
Win32_NetworkAdapter
Win32_NetworkAdapterConfiguration
WIN32_NetworkClient
Win32_NetworkConnection
Win32_NetworkLoginProfile
Win32_NetworkProtocol
Win32_NTDomain
Win32_NTEventlogFile
Win32_NTLogEvent
Win32_OnBoardDevice
Win32_OperatingSystem
Win32_OSRecoveryConfiguration
Win32_PageFileSetting
Win32_PageFileUsage
Win32_PerfRawData_PerfNet_Server
Win32_PhysicalMemoryArray
Win32_PingStatus
Win32_PortConnector
Win32_PortResource
Win32_Printer
Win32_PrinterConfiguration
Win32_PrintJob
Win32_Process
WIN32_PROCESSOR
Win32_ProcessXXX
Win32_Product
Win32_QuickFixEngineering
Win32_QuotaSetting
Win32_Registry
Win32_ScheduledJob
Win32_SCSIController
Win32_Service
Win32_Share
Powershell Plus
Win32_SoftwareElement
Win32_SoftwareFeature
WIN32_SoundDevice
Win32_StartupCommand
Win32_SystemAccount
Win32_SystemDriver
Win32_SystemEnclosure
Win32_SystemSlot
Win32_TapeDrive
Win32_TemperatureProbe
Win32_TimeZone
Win32_UninterruptiblePowerSupply
Win32_UserAccount
Win32_VoltageProbe
Win32_VolumeQuotaSetting
Win32_WMISetting
When you run Get-WmiHelpLocation, it opens the web page in your default browser that documents the WMI class you specified, and also
returns the URL:
:
:
:
:
:
__PROPERTY_COUNT
__DERIVATION
__SERVER
__NAMESPACE
__PATH
:
:
:
:
:
2
SoftwareLicensingService
SoftwareLicensingService
SoftwareLicensingService.Version=
6.1.7601.17514
32
{}
TOBIASAIR1
root\cimv2
\\TOBIASAIR1\root\cimv2:SoftwareLi
censingService.Version=6.1.7601.1
7514
ClientMachineID
:
DiscoveredKeyManagementServiceMachineName
:
DiscoveredKeyManagementServiceMachinePort
: 0
IsKeyManagementServiceMachine
: 0
KeyManagementServiceActivationDisabled
: False
KeyManagementServiceCurrentCount
: 4294967295
KeyManagementServiceDnsPublishing
: True
KeyManagementServiceFailedRequests
: 4294967295
KeyManagementServiceHostCaching
: True
KeyManagementServiceLicensedRequests
: 4294967295
KeyManagementServiceListeningPort
: 0
KeyManagementServiceLowPriority
: False
KeyManagementServiceMachine
:
KeyManagementServiceNonGenuineGraceRequests : 4294967295
KeyManagementServiceNotificationRequests
: 4294967295
KeyManagementServiceOOBGraceRequests
: 4294967295
KeyManagementServiceOOTGraceRequests
: 4294967295
KeyManagementServicePort
: 1688
KeyManagementServiceProductKeyID
:
KeyManagementServiceTotalRequests
: 4294967295
KeyManagementServiceUnlicensedRequests
: 4294967295
PolicyCacheRefreshRequired
: 0
RemainingWindowsReArmCount
: 3
RequiredClientCount
: 4294967295
TokenActivationAdditionalInfo
:
TokenActivationCertificateThumbprint
:
TokenActivationGrantNumber
: 4294967295
TokenActivationILID
:
TokenActivationILVID
: 4294967295
Version
: 6.1.7601.17514
VLActivationInterval
: 4294967295
VLRenewalInterval
: 4294967295
PSComputerName
: TOBIASAIR1
You can also check the license status of your copy of Windows:
Get-WmiObject SoftwareLicensingProduct |
Select-Object -Property Description, LicenseStatus |
Out-GridView
And you can find out which Windows SKU you are actually using:
PS> Get-WmiObject SoftwareLicensingProduct |
Where-Object { $_.LicenseStatus -eq 1 } |
Select-Object -Property Name, Description
Name
---Windows(R) 7, Ultimate edition
Description
----------Windows Operating System - Windows(R...
:
:
:
:
:
__PROPERTY_COUNT
__DERIVATION
__SERVER
__NAMESPACE
__PATH
:
:
:
:
:
displayName
instanceGuid
pathToSignedProductExe
:
:
:
pathToSignedReportingExe :
productState
PSComputerName
:
:
2
AntiVirusProduct
AntiVirusProduct
AntiVirusProduct.instanceGuid={641105E6-77ED-3F35-A3
04-765193BCB75F}
5
{}
TOBIASAIR1
ROOT\SecurityCenter2
\\TOBIASAIR1\ROOT\SecurityCenter2:AntiVirusProduct.in
stanceGuid={641105E6-77ED-3F35-A304-765193BCB75F}
Microsoft Security Essentials
{641105E6-77ED-3F35-A304-765193BCB75F}
C:\Program Files\Microsoft Security
Client\msseces.exe
C:\Program Files\Microsoft Security
Client\MsMpEng.exe
397312
TOBIASAIR1
:
:
:
:
:
:
:
BCM43XX
68:A8:6D:0B:5F:CC
Ethernet 802.3
7
Broadcom 802.11n Network Adapter
13000000
This gets you the network hardware but not the network configuration. To get the configuration data for this network card (like its IP
address), get the related Win32_NetworkAdapterConfiguration instance:
function Get-NetworkConfig {
Get-WmiObject Win32_NetworkAdapter -Filter NetConnectionStatus=2 |
ForEach-Object {
$result = 1 | Select-Object Name, IP, MAC
$result.Name = $_.Name
$result.MAC = $_.MacAddress
$config = $_.GetRelated(Win32_NetworkAdapterConfiguration)
$result.IP = $config | Select-Object -ExpandProperty IPAddress
$result
}
}
Get-NetworkConfig
Next, you can use the -contains operator to check whether a specific drive exists:
PS> $drives -contains C:
True
PS> $drives -contains P:
False
Note that both examples limit information to only the Name property. You can get back any kind of information, such as file size and write
times:
Get-WmiObject CIM_DataFile -Filter Drive=C: and Path=\\Windows\\ and Extension=log|
Select-Object -Property *
Get-WmiObject CIM_DataFile -Filter Drive=C: and Path=\\Windows\\|
Select-Object -Property Name, FileType, FileSize, EightDotThreeFileName
Avoid using the like operator. You can use it to find files recursively, but this can lead to very large result sets, and it can fail if a folder
contains illegal path names (such as path names longer than 256 characters).
The next line would get you all text files in the folder c:\temp (which must exist of course) and all of its subfolders
Get-WmiObject CIM_DataFile -Filter Drive=C: and Path like \\temp\\% and Extension=txt |
Select-Object -Property Caption, EightDotThreeFileName, FileSize
Note again that these WMI queries can fail or report cryptic errors if file paths exceed the 256 character file path length.
Likewise, you can convert WMI date and time information back to a regular date and time object. This code tells you when your system
was rebooted the last time:
$os = Get-WmiObject -Class Win32_OperatingSystem
$bootTime = $os.LastBootUpTime
$bootTimeNice = [System.Management.ManagementDateTimeConverter]::ToDateTime($bootTime)
The raw WMI date and time information would look like this:
PS> $bootTime
20130825072242.307198+120
The converted date and time however is much more readable:
PS> $bootTimeNice
Sunday, August 25, 2013 7:22:42 AM
Using the -f formatting operator, it is easy to fill in the requested information by reading the Caption and FreeSpace property. Note that you
can convert the bytes to megabytes by dividing bytes by 1MB. If you wanted gigabytes, change 1MB to 1GB. Just make sure you dont have
a space between number and unit. 1 MB will not work.
Function Restart-NetworkAdapter
{
param
(
$NetworkName
)
Disable-NetworkAdapter $NetworkName
Enable-NetworkAdapter $NetworkName
}
Try this to reset a network adapter:
Restart-NetworkAdapter LAN-Connection
A restart will require Administrator privileges. Otherwise, you will receive error code 5 (Access Denied).
System.Management.ManagementObject#root\cimv2\CIM_SoftwareElement
System.Management.ManagementObject#root\cimv2\CIM_LogicalElement
System.Management.ManagementObject#root\cimv2\CIM_ManagedSystemElement
System.Management.ManagementObject#Win32_BIOS
System.Management.ManagementObject#CIM_BIOSElement
System.Management.ManagementObject#CIM_SoftwareElement
System.Management.ManagementObject#CIM_LogicalElement
System.Management.ManagementObject#CIM_ManagedSystemElement
System.Management.ManagementObject
System.Management.ManagementBaseObject
System.ComponentModel.Component
System.MarshalByRefObject
System.Object
In contrast to GetType(), this property will work for all objects, including COM objects. The most specific type is always found at the
beginning of that array:
(Get-WmiObject Win32_BIOS).PSTypeNames[0]
TimeGenerated
------------01.09.2013 16:14:15
01.09.2013 16:13:16
17.08.2013 13:39:27
17.08.2013 13:38:30
05.08.2013 20:03:35
05.08.2013 20:02:37
21.07.2013 10:15:05
21.07.2013 10:15:05
TobiasAir1\Tobias
TobiasAir1\Tobias
NT AUTHORITY\SYSTEM
TobiasAir1\Tobias
TobiasAir1\Tobias
NT AUTHORITY\NETWORK SERVICE
TobiasAir1\Tobias
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
TobiasAir1\Tobias
TobiasAir1\Tobias
if ($Owner.ReturnValue -eq 2)
{
$result.Owner = Access Denied
}
else
{
$result.Owner = {0}\{1} -f ($Owner.Domain, $Owner.User)
}
$result
}
}
So if you wanted to know who is running PowerShell on your system, check this out:
PS> Get-ProcessEx power*exe
Name
---powershell_ise.exe
powershell_ise.exe
Owner
----TobiasAir1\Tobias
TobiasAir1\Tobias
Description
----------powershell_ise.exe
powershell_ise.exe
Handle
-----6056
7392
Likewise, you can now check who is currently visiting your computer through PowerShell Remoting. Just look for processes named
wsmprovhost.exe.
These lines assign a new user account and password for the Spooler service. Note that your account will need special privileges to be
able to do that. If you get an access denied error, open services.msc and try to change the account manually using the GUI. You will get a
message if your account lacks the necessary privileges and the privileges are added.
FormFactor
---------12
12
MemoryType
---------0
0
SODIMM
SODIMM
Unknown
Unknown
127.0.0.1 |
ForEach-Object {
$time = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime((Get-Date).AddHours(-24))
Get-WmiObject Win32_NTLogEvent -ComputerName $_ -Filter EventType=1 and TimeGenerated>=$time |
ForEach-Object {
$_ | Add-Member NoteProperty TimeStamp (
[System.Management.ManagementDateTimeConverter]::ToDateTime($_.TimeWritten)) ; $_
}
} |
Select-Object __SERVER, LogFile, Message, EventCode, TimeStamp |
ConvertTo-Html -Head $head -Body $header -Title $title |
Out-File $home\report.htm
Invoke-Item $home\report.htm
:
:
:
:
True
2
{7, 11, 12, 15...}
MBA41.88Z.0077.B0E.1110141154
So you can now use Select-Object to combine information from both WMI classes into one tabl So you can now use Select-Object to combine information from both WMI classes into one table:
PS> $os | Select-Object Caption, OSArchitecture, SerialNumber, SMBIOSBIOSVersion
Caption
OSArchitecture
-------------------Microsoft Windows... 64-bit
SerialNumber
SMBIOSBIOSVersion
---------------------------00426-069-126489... MBA41.88Z.0077.B...
When you send $os to Select-Object and specify *, you get a list of all of the combined properties:
$os | Select-Object -Property *
-Credential Administrator
Whenever you need to use this credential, you should import it:
$cred = Import-Credential -Path $env:temp\cred.xml
Get-WmiObject Win32_BIOS -ComputerName storage1 -Credential $cred
Note that your password is encrypted and can only be imported by the same user that exported it.
$htmlEnd = </body></html>
$htmlStart
Get-WmiObject -Class CIM_PhysicalElement |
Group-Object -Property __Class |
ForEach-Object {
$_.Group |
Select-Object -Property * |
ConvertTo-Html -Fragment -PreContent (<h3>{0}</h3> -f $_.Name )
}
$htmlEnd
}
And this is how you would call the function and create a report:
$path = $env:temp\report.hta
Get-SystemReport | Out-File -Filepath $path
Invoke-Item $path
Your system is in good shape if this line does not return any results. Orphaned shares can occur when a shared folder is deleted in a lowlevel way, or when you disconnect hard drives.
ReturnType
---------UInt32
UInt32
UInt32
UInt32
Parameters
---------{Access, Descrip...
{Access, Descrip...
{}
{}
Qualifiers
---------{Constructor, Im...
{Implemented, Ma...
{Implemented, Ma...
{Destructor, Imp...
ReturnType Parameters
Qualifiers
---------- ------------------UInt32 {Access, Descrip... {Constructor, Im...
PS>
PS> $class.CimClassMethods[Create].Parameters
Name
---Access
Description
MaximumAllowed
Name
Password
Path
Type
CimType
------Instance
String
UInt32
String
String
String
UInt32
Qualifiers
ReferenceClassName
--------------------------{EmbeddedInstanc...
{ID, In, Mapping...
{ID, In, Mapping...
{ID, In, Mapping...
{ID, In, Mapping...
{ID, In, Mapping...
{ID, In, Mapping...
Note that some of the information is not displayed. Send the information to Out-GridView to see everything.
From this, you can now construct the command that would create new shares:
$args = @{
Name=myTestshare
Path=c:\
MaximumAllowed=[UInt32]4
Type=[UInt32]0
}
Invoke-CimMethod -ClassName Win32_Share -MethodName Create -Arguments $args
Note that you may need Administrator privileges. A return code of 0 indicates success. A return code of 2 reports Access Denied,
and a code of 22 indicates that there is already a share under the name you picked. The meaning of these error codes is specific to the
WMI class and method you use.
function Get-BIOS
{
param($ComputerName, $Credential)
Get-WmiObject -Class Win32_BIOS @PSBoundParameters
}
This Get-BIOS function will get the computer BIOS information and supports -ComputerName and -Credential for remote access, too.
Make sure you run the function and test it.
Next, turn the function into a module:
$name = Get-BIOS
New-Item -Path $home\Documents\WindowsPowerShell\Modules\$name\$name.psm1 -ItemType File -Force
-Value function $name { $((Get-Item function:\$name).Definition) }
Just make sure $name contains the name of your function, and you ran your function so it is in memory.
Now why is this conversion important? Because PowerShell 3.0 auto-detects functions in modules! So if you use PowerShell 3.0 and have
created the mini module, open up a new PowerShell and type:
PS> Get-BIOS
SMBIOSBIOSVersion
Manufacturer
Name
SerialNumber
Version
:
:
:
:
:
MBA41.88Z.0077.B0E.1110141154
Apple Inc.
Default System BIOS
C02GW04RDRQ4
APPLE - 60
Bam! Your function is now available automatically, and you can easily add new functionality.