Tag: WMI
Windows Management Framework 3.0 – Community Technology Preview 1
The WMF 3.0 CTP1 for Windows 7 SP1 and Windows Server 2008 R2 SP1 (download) is out (was published yesterday) and brings updated management functionality. It contains Windows PowerShell 3.0 and new versions of WMI and WinRM. Please note that a CTP isn’t a final release but a preview release. It is designed to enable the community to experience and review the preliminary designs and direction of key features and to solicit feedback before features are finalized.
Some of the new features in Windows PowerShell 3.0 enable Service Providers to automatically build, maintain, and administer IT Infrastructures. With WMF 3.0 including PowerShell 3.0, WMI, and WinRM, Microsoft addresses the increasing need for automation driven by the era of Cloud Computing.
Working with local administrator
When working with local administrator account, there are 3 possible tasks you usually want to accomplish:
1.) Change password
2.) Rename account
3.) Disable\Enable account
Below are snippets of Powershell code that can help you to achieve that. First line is always used to retrieve local account with RID 500 (built-in administrator account, no matter what is the name), rest than depends on what you want to achieve.
1.) Change password
<P>$LocalAdministrator = $(Get-WmiObject –Query ‘Select * from Win32_UserAccount
Where (LocalAccount="True" and SID like "%-500")’)</P>
<P>$AdminReference = [adsi]("WinNT://./" + $LocalAdministrator.Name + ", user")
$AdminReference.psbase.invoke("SetPassword", "new and shiny password")</P>
2.) Rename account
<P>$LocalAdministrator = $(Get-WmiObject –Query ‘Select * from Win32_UserAccount
Where (LocalAccount="True" and SID like "%-500")’)</P>
<P>$LocalAdministrator.Rename("LocalAdmin")</P>
<P>$LocalAdministrator.Put()</P>
3.) Disable\Enable account
<P>$LocalAdministrator = $(Get-WmiObject –Query ‘Select * from Win32_UserAccount Where (LocalAccount="True" and SID like "%-500")’)</P> <P>$LocalAdministrator.Disabled = $False</P> <P>$LocalAdministrator.Put()</P>
Martin
How To Reset A Wireless Network Adapter?
I switch between wireless networks frequently. Usually I am facing issues with getting connected which get resolved by clicking around in Vista’s Network and Sharing Center. As this takes always a couple of minutes I want a PowerShell script that I can use to reset my wireless lan adapter directly.
This can be accomplished using WMI:
# NAME # Reset-Wlan.ps1 # # SYNOPSIS # Disables, pauses, and then enables the wlan adapter # # SYNTAX # .\Reset-Wlan.ps1 # # REMARKS # Run this script elevated # # AUTHOR # Frank-Peter Schultze www.fpschultze.de # # DATE # 15-Mar-2009 # $wlan = Get-WmiObject -Class Win32_NetworkAdapter -Filter "Name LIKE '%wireless%'" $wlan.Disable() # Maybe waste of time. Never mind! Start-Sleep -Seconds 10 $wlan.Enable()
How To Map A Network Printer?
If you want to add a network printer connection with PowerShell try one of the following ways:
Printui.dll Call
$PrinterPath = "\\machine\printer" rundll32.exe printui.dll,PrintUIEntry /q /in /n$PrinterPath
Use WshNetwork’s AddWindowsPrinterConnection method
PrinterPath = "\\machine\printer" (New-Object -ComObject WScript.Network).AddWindowsPrinterConnection($PrinterPath)
Use WMI Win32_Printer’s AddPrinterConnection method
PrinterPath = "\\machine\printer" ([wmiclass]"Win32_Printer").AddPrinterConnection($PrinterPath)
How To Retrieve The UUID/GUID From A Computer?
The VBScript function below, GetUUID, shows how to retrieve the UUID/GUID from a computer.
' Test it
WScript.Echo GetUUID(".")
Function GetUUID(strComputer)
Dim objWmi, colItems, objItem, strUUID, blnValidUUID
Set objWmi = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWmi.ExecQuery("Select * from Win32_ComputerSystemProduct")
strUUID = ""
blnValidUUID = False
For Each objItem in colItems
strUUID = objItem.UUID
If Not IsEmpty(strUUID) OR Not IsNull(strUUID) Then
If (strUUID <> "00000000-0000-0000-0000-000000000000") AND _
(strUUID <> "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF") Then
blnValidUUID = True
Exit For
End If
End If
Next
Set objWmi = Nothing
If Not blnValidUUID Then
Set colItems = GetObject("winmgmts:" & strComputer & "\root\cimv2").InstancesOf("Win32_NetworkAdapter")
For Each objItem In colItems
If (objItem.AdapterType = "Ethernet 802.3") Then
If (objItem.Description <> "Packet Scheduler Miniport") Then
strUUID = "00000000-0000-0000-0000-" & Replace(objItem.MACAddress, ":", "")
Exit For
End If
End If
Next
Set NicSet = Nothing
End If
GetUUID = strUUID
End Function
How To Enable DHCP Completely?
The Sub procedure below uses WMI in order to set the network adapter’s IP configuration to DHCP, not only for IP address, IP gateway, and subnet mask, but also for both DNS server search order and WINS servers:
Sub AutoIpConfig
Const LOCAL_MACHINE = "."
Dim objWmi, colItems, objItem, intError
Set objWmi =WshGetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& LOCAL_MACHINE & "\root\cimv2")
Set colItems = objWmi.ExecQuery( _
"Select * from Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objItem In colItems
intError = objItem.EnableDHCP()
If (intError <> 0) Then
CriticalErrorBox "Could not enable DHCP."
End If
objItem.SetDNSServerSearchOrder Null
objItem.SetWINSServer Null, Null
Exit For
Next
End Sub
If you omit the SetDNSServerSearchOrder and SetWINSServer statements the previously configured DNS and WINS servers will remain in the network adapter’s IP configuration.
How To Determine The Name Of The Local Administrator Group?
The VBScript below, LocalAdminGroup.vbs, determines the name of the local administrator group by searching its SID in the list of local groups.
' ===================================================================
' Filename : LocalAdminGroup.vbs
' Revision : 1.0
' Datum : 21.11.2005
' Author : Frank-Peter Schultze
'
' Determines and shows the name of the local administrators group.
'
' ===================================================================
Option Explicit
Dim WshShell, strName, objWmi, colGroups, objGroup
Set WshShell = WScript.CreateObject("Wscript.Shell")
strName = WshShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
Set objWmi = GetObject("winmgmts:\\" & strName & "\root\cimv2")
Set colGroups = objWmi.ExecQuery ("Select * From Win32_Group Where Domain = '" _
& strName & "' AND SID = 'S-1-5-32-544'")
For Each objGroup in colGroups
Wscript.Echo objGroup.Name
Next
See also: Well-known security identifiers in Windows operating systems
How To Test WMI Connectivity?
The VBScript file below, WMIPing.vbs, checks if connection to WMI of the target system can be established.
WMIPing.vbs exits with an errorlevel:
- 0 = WMI Ping succeeded successfully
- 1 = ICMP Ping failed, WMI Ping omitted
- 2 = WMI Ping failed
' ___________________________________________________________________
'
' VBScript File: WMIPing.vbs
' Author: Frank-Peter Schultze
'
' Updates: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=79
' Enhancement Req.
' and Bug Reports: support@fpschultze.de
'
' Built/Tested On: Windows XP Prof.
' Requirements: OS: Windows 2000+ w/ WMI service started
'
' Purpose: Check if connection to WMI of the target system
' can be established
'
' Syntax:
'
' wmiping [systemname] [/n:namespace] [/u:account /p:password] [/q]
'
' systemname IP address, full DNS name, or NetBIOS name of
' the target system (default: localhost)
' /n:namespace WMI namespace (default: root\cimv2)
' /u:account Account to be used to connect to WMI
' /p:password Password from 'username'
' /q Quiet mode (no console output)
'
' State Changes:
'
' Possible errorlevels
'
' 0 WMI Ping succeeded successfully
' 1 ICMP Ping failed, WMI Ping omitted
' 2 WMI Ping failed
'
' Assumptions And
' Limitations: -
'
' Last Update: 10:47 23.07.2008
' ___________________________________________________________________
'
Option Explicit
On Error Resume Next
Const DEFAULT_COMPUTER = "localhost"
Const DEFAULT_NAMESPACE = "root\cimv2"
Dim objLoc
Dim objWmi
Dim strSysname
Dim strNamespace
Dim strUsername
Dim strPassword
Dim blnQuiet
strSysname = DEFAULT_COMPUTER
strNamespace = DEFAULT_NAMESPACE
strUsername = ""
strPassword = ""
blnQuiet = False
Call subParseArgs(WScript.Arguments, strSysname, strNamespace, strUsername, strPassword, blnQuiet)
If fctIsAlive(strSysname) Then
If Not blnQuiet Then
WScript.Echo "ICMP Ping for " & strSysname & " passed."
WScript.Echo "Connecting to namespace " & strNamespace & " . . ."
End If
Set objLoc = WScript.CreateObject("WbemScripting.SWbemLocator")
Set objWmi = objLoc.ConnectServer(strSysname, strNamespace, strUsername, strPassword)
If Err.Number Then
If Not blnQuiet Then
WScript.Echo "Unable to connect to WMI: " & Err.Description
End If
Err.Clear
WScript.Quit(2)
Else
Set objWmi = Nothing
Set objLoc = Nothing
If Not blnQuiet Then
WScript.Echo "WMI successfully connected."
End If
WScript.Quit(0)
End If
Else
If Not blnQuiet Then
WScript.Echo "ICMP Ping for " & strSysname & " failed."
End If
WScript.Quit(1)
End If
Function fctIsAlive(strHostOrIP)
Dim objSh, objCmd, strCmd
strCmd = "%ComSpec% /C %SystemRoot%\system32\ping.exe -n 1 " & strHostOrIP & " | " _
& "%SystemRoot%\system32\find.exe /c /i " & Chr(34) & "ttl=" & Chr(34)
Set objSh = WScript.CreateObject("WScript.Shell")
Set objCmd = objSh.Exec(strCmd)
fctIsAlive = CBool(Trim(objCmd.StdOut.ReadAll))
Set objCmd = Nothing
Set objSh = Nothing
End Function
Sub subParseArgs(objArgs, strSysname, strNamespace, strUsername, strPassword, blnQuiet)
Dim i
Dim strArg
Dim blnNamed
For i = 0 To objArgs.Count - 1
strArg = Split(objArgs(i), ":")
blnNamed = UBound(strArg)
Select Case Left(strArg(0), 1)
Case "/", "-"
Select Case UCase(strArg(0))
Case "/?", "/H", "-?", "-H"
Call subUsageBox("help", True)
Case "/N", "-N"
If blnNamed Then
strNamespace = Trim(strArg(1))
Else
Call subUsageBox("syntax error", True)
End If
Case "/U", "-U"
If blnNamed Then
strUsername = Trim(strArg(1))
Else
Call subUsageBox("syntax error", True)
End If
Case "/P", "-P"
If blnNamed Then
strPassword = Trim(strArg(1))
Else
Call subUsageBox("syntax error", True)
End If
Case "/Q", "-Q"
If blnNamed Then
Call subUsageBox("syntax error", True)
Else
blnQuiet = True
End If
Case Else
Call subUsageBox("unknown argument: " & strArg(0), True)
End Select
Case Else
If blnNamed Then
Call subUsageBox("syntax error", True)
Else
strSysname = Trim(strArg(0))
End If
End Select
Next
End Sub
Sub subUsageBox(strTitle, blnQuit)
Dim strUsage
strUsage = WScript.ScriptName & " initially pings the target system. If the ping is successful " & vbNewLine
strUsage = strUsage & "it connects to the target system using WMI." & vbNewLine & vbNewLine
strUsage = strUsage & "Usage: " & WScript.ScriptName & " [systemname] [/n:namespace] [/u:account /p:password] [/q]" & vbNewLine & vbNewLine
strUsage = strUsage & " systemname" & vbTab & "IP address, full DNS name, or NetBIOS name of the" & vbNewLine
strUsage = strUsage & vbTab & vbTab & "target system (default: " & DEFAULT_COMPUTER & ")" & vbNewLine
strUsage = strUsage & " /n:namespace" & vbTab & "WMI namespace (default: " & DEFAULT_NAMESPACE & ")" & vbNewLine
strUsage = strUsage & " /u:account" & vbTab & "Account to be used to connect to WMI" & vbNewLine
strUsage = strUsage & " /p:password" & vbTab & "Password from 'username'" & vbNewLine
strUsage = strUsage & " /q" & vbTab & vbTab & "Quiet mode (no console output)" & vbNewLine & vbNewLine
strUsage = strUsage & "Possible errorlevels:" & vbNewLine & vbNewLine
strUsage = strUsage & " 0" & vbTab & "WMI Ping succeeded successfully." & vbNewLine
strUsage = strUsage & " 1" & vbTab & "ICMP Ping failed, WMI Ping omitted." & vbNewLine
strUsage = strUsage & " 2" & vbTab & "WMI Ping failed"
Call MsgBox(strUsage, vbOKOnly + vbInformation, WScript.ScriptName & " - " & strTitle)
If blnQuit Then
WScript.Quit
End If
End Sub