When working with Windows systems across an
enterprise, the question often arises: "How do I do
<some task> in
PowerShell?" In an administrator's perfect world, anybody who
designs a feature with management implications also supports (via
PowerShell cmdlets) the tasks that manage that feature. Many management
tasks have been around longer than PowerShell, though, so the answer can
sometimes be, "The same way you did it before
PowerShell."
That's not to say that your life as an administrator doesn't improve with the introduction of PowerShell, however. Pre-PowerShell administration tasks generally fall into one of several models: command-line utilities, Windows Management Instrumentation (WMI) interaction, registry manipulation, file manipulation, interaction with COM objects, or interaction with .NET objects.
That's not to say that your life as an administrator doesn't improve with the introduction of PowerShell, however. --> However, that's not to say that your life as an administrator doesn't improve with the introduction of PowerShell.
PowerShell makes it easier to interact with all these task models, and therefore makes it easier to manage functionality that depends on them.
Use the -DomainName
parameter of the Add-Computer cmdlet to add a
computer to a domain. Use the -WorkGroupName
parameter to add it to a workgroup.
PS > Add-Computer -DomainName MyDomain -Credential MyDomain\MyUser PS > Restart-Computer
While fairly self-descriptive, the
Add-Computer cmdlet lets you add a computer to a
domain or workgroup. Since a domain join only takes effect once you
restart the computer, always call the
Restart-Computer cmdlet after joining a
domain.
Perhaps the most complex parameter of the
Add-Computer cmdlet is the
-Unsecure parameter. When you add a computer to a
domain, a machine account is normally created with a unique password. An
unsecure join (as enabled by the -Unsecure parameter)
instead uses a default password: the first fourteen characters of the
computer name, in lower case. Once the domain join is complete, the
system automatically changes the password. This is primarily intended
for unattended installations.
compex --> complex
To remove a computer from a domain, see the section called “Remove a Computer from a Domain”.
Use the Remove-Computer
cmdlet to depart a domain.
PS > Remove-Computer PS > Restart-Computer
The Remove-Computer lets
you remove the current computer from a domain. Once you do so, it
reverts back to its default workgroup. Since domain changes only take
effect once you restart the computer, always call the
Restart-Computer cmdlet after departing a
domain.
Once you remove a computer from a domain, you can no longer use domain credentials to manage that computer. Before departing a domain, make sure that you know (or create) a local administrator's account for that machine.
To re-join a domain, see the section called “Join a Computer to a Domain or Workgroup”.
The Group Policy system in Windows stores logon
and logoff scripts under the registry keys HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group
Policy\State\<User SID>\Scripts\Logon and HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group
Policy\State\<User SID>\Scripts\Logoff. Each key has a subkey for each
group policy object that applies. Each of those child keys has another
level of keys that correspond to individual scripts that apply to the
user.
This can be difficult to investigate when you don't know the SID of the user in question, so Example 27.1, “Get-UserLogonLogoffScript.ps1” automates the mapping of username to SID, as well as all the registry manipulation tasks required to access this information.
Example 27.1. Get-UserLogonLogoffScript.ps1
##############################################################################
param(
$username = $(throw "Please specify a username"),
$scriptType = $(throw "Please specify the script type")
)
$scriptOptions = "Logon","Logoff"
if($scriptOptions -notcontains $scriptType)
{
$error = "Cannot convert value {0} to a script type. " +
"Specify one of the following values and try again. " +
"The possible values are ""{1}""."
$ofs = ", "
throw ($error -f $scriptType, ([string] $scriptOptions))
}
$account = New-Object System.Security.Principal.NTAccount $username
$sid =
$account.Translate([System.Security.Principal.SecurityIdentifier]).Value
$registryKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\" +
"Group Policy\State\$sid\Scripts"
foreach($policy in Get-ChildItem $registryKey\$scriptType)
{
foreach($script in Get-ChildItem $policy.PsPath)
{
Get-ItemProperty $script.PsPath | Select Script,Parameters
}
}For more information about working with the Windows Registry in PowerShell, see Chapter 21, The Windows Registry. For more information about running scripts, see the section called “Run Programs, Scripts, and Existing Tools”.
The Group Policy system in Windows stores
startup and shutdown scripts under the registry keys HKLM:\SOFTWARE\Policies\Microsoft\Windows\System\Scripts\Startup
and HKLM:\SOFTWARE\Policies\Microsoft\Windows\System\Scripts\Shutdown.
Each key has a subkey for each group policy object that applies. Each of
those child keys has another level of keys that correspond to individual
scripts that apply to the machine.
Example 27.2, “Get-MachineStartupShutdownScript.ps1” allows you to easily retrieve and access the startup and shutdown scripts for a machine.
Example 27.2. Get-MachineStartupShutdownScript.ps1
##############################################################################
param(
$scriptType = $(throw "Please specify the script type")
)
$scriptOptions = "Startup","Shutdown"
if($scriptOptions -notcontains $scriptType)
{
$error = "Cannot convert value {0} to a script type. " +
"Specify one of the following values and try again. " +
"The possible values are ""{1}""."
$ofs = ", "
throw ($error -f $scriptType, ([string] $scriptOptions))
}
$registryKey = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System\Scripts"
foreach($policy in Get-ChildItem $registryKey\$scriptType)
{
foreach($script in Get-ChildItem $policy.PsPath)
{
Get-ItemProperty $script.PsPath | Select Script,Parameters
}
}For more information about working with the Windows Registry in PowerShell, see Chapter 21, The Windows Registry. For more information about running scripts, see the section called “Run Programs, Scripts, and Existing Tools”.
You want to use a PowerShell script in a logon, logoff, startup, or shutdown script.
In Windows 7 (and Windows Server 2008 R2),
simply add a new script in the PowerShell Scripts
tab.
For other operating systems, open the
Scripts tab, and click "Add a
Script." Use powershell.exe as the script
name, and the following as its parameters:
-NoProfile -NonInteractive -ExecutionPolicy ByPass -File "<script>"arguments
Before PowerShell version two, launching a
PowerShell script as a Group Policy script was a difficult task. While
you could use the -Command parameter of
powershell.exe to invoke a command, the quoting rules
made it difficult to specify the script correctly. After getting the
quoting rules correct, you still had to contend with the Execution
Policy of the client computer.
In the timeframe of PowerShell version two, the situation improved significantly. First of all, Group Policy now supports PowerShell scripts as a first-class citizen for the four different user and computer scripts.
When Group Policy's native support is not an
option, PowerShell.exe includes several new
parameters that make it easier to control the execution environment:
-ExecutionPolicy, and -File. For
more information about these (and PowerShell's other) parameters, see
the section called “Invoke a PowerShell Command or Script From Outside
PowerShell”.
To manage the Windows Firewall, use the
LocalPolicy.CurrentProfile.FirewallEnabled
property of the HNetCfg.FwMgr COM
object:
PS > $firewall = New-Object -com HNetCfg.FwMgr PS > $firewall.LocalPolicy.CurrentProfile.FirewallEnabled = $true PS > $firewall.LocalPolicy.CurrentProfile.FirewallEnabled True
The HNetCfg.FwMgr COM object provides programmatic
access to the Windows Firewall in Windows XP SP2 and later. The LocalPolicy.CurrentProfile property provides
the majority of its functionality.
For more information about managing the Windows Firewall through its COM API, visit http://msdn.microsoft.com and search for "Using Windows Firewall API." The documentation provides examples in VBScript but gives a useful overview of the functionality available.
If you are unfamiliar with the VBScript-specific portions of the documentation, the Microsoft Script Center provides a useful guide to help you convert from VBScript to PowerShell. You can find that document at: http://www.microsoft.com/technet/scriptcenter/topics/winpsh/convert/default.mspx.
For more information about working with COM objects in PowerShell, see the section called “Automate Programs Using COM Scripting Interfaces”.
To open or close ports in the Windows
Firewall, use the LocalPolicy.
CurrentProfile.GloballyOpenPorts collection of the HNetCfg.FwMgr COM object.
To add a port, create a HNetCfg.FWOpenPort COM object to represent the
port, and then add it to the GloballyOpenPorts collection:
$PROTOCOL_TCP = 6 $firewall = New-Object -com HNetCfg.FwMgr $port = New-Object -com HNetCfg.FWOpenPort $port.Name = "Webserver at 8080" $port.Port = 8080 $port.Protocol = $PROTOCOL_TCP $firewall.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add($port)
To close a port, remove it from the GloballyOpenPorts collection:
$PROTOCOL_TCP = 6 $firewall.LocalPolicy.CurrentProfile.GloballyOpenPorts.Remove(8080, $PROTOCOL_TCP)
The HNetCfg.FwMgr COM object provides programmatic
access to the Windows Firewall in Windows XP SP2 and later. The LocalPolicy.CurrentProfile property provides
the majority of its functionality.
For more information about managing the Windows Firewall through its COM API, visit http://msdn.microsoft.com and search for "Using Windows Firewall API." The documentation provides examples in VBScript but gives a useful overview of the functionality available.
If you are unfamiliar with the VBScript-specific portions of the documentation, the Microsoft Script Center provides a useful guide to help you convert from VBScript to PowerShell. You can find that document at http://www.microsoft.com/technet/scriptcenter/topics/winpsh/convert/default.mspx.
For more information about working with COM objects in PowerShell, see the section called “Automate Programs Using COM Scripting Interfaces”.
The best place to find information about
currently installed software is actually from the place that stores
information about how to uninstall it: the HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
registry key.
Each child of that registry key represents a
piece of software you can uninstall—traditionally through the Add/Remove
Programs entry in the Control Panel. In addition to the DisplayName of the application, other useful
properties usually exist (depending on the application). Examples include
Publisher, UninstallString, and HelpLink.
To see all the properties available from software installed on your system, type the following:
$properties = Get-InstalledSoftware |
Foreach-Object { $_.PsObject.Properties }
$properties | Select-Object Name | Sort-Object -Unique NameThis lists all properties mentioned by at least one installed application (although very few are shared by all installed applications).
To work with this data, though, you first need to retrieve it. Example 27.3, “Get-InstalledSoftware.ps1” provides a script to list all installed software on the current system, returning all information as properties of PowerShell objects.
Example 27.3. Get-InstalledSoftware.ps1
##############################################################################
param(
$displayName = ".*"
)
$keys = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
$items = $keys | Foreach-Object { Get-ItemProperty $_.PsPath }
foreach($item in $items)
{
if(($item.DisplayName) -and ($item.DisplayName -match $displayName))
{
$item
}
}
For more information about working with the Windows Registry in PowerShell, see Chapter 21, The Windows Registry. For more information about running scripts, see the section called “Run Programs, Scripts, and Existing Tools”.
To uninstall an application, use the Get-InstalledSoftware script provided in the section called “Program: List All Installed Software” to retrieve the command
that uninstalls the software. Since the UninstallString uses batch file syntax, use
cmd.exe to launch the
uninstaller:
PS > $software = Get-InstalledSoftware UnwantedProgram
PS > cmd /c $software.UninstallStringAlternatively, use the Win32_Product WMI class for an unattended
installation:
$application = Get-WmiObject Win32_Product -filter "Name='UnwantedProgram'" $application.Uninstall()
The UninstallString provided by applications
starts the interactive experience you would see if you were to uninstall
the application through the Add/Remove Programs entry in the Control
Panel. If you need to remove the software in an unattended manner, you
have two options: use the "quiet mode" of the application's uninstaller
(for example, the /quiet switch to
msiexec.exe), or use the software
removal functionality of the Win32_Product WMI class as demonstrated in the
solution.
For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
You want to create a computer restore point, restore a computer to a previous restore point, or manage the schedule for automatic restore points.
Use the
Enable-ComputerRestore and
Disable-ComputerRestore cmdlets to enable and disable
automatic computer checkpoints. Use the
Get-ComputerRestorePoint and
Restore-Computer cmdlets to list all restore points,
and to restore a computer to one of them. Use the
Checkpoint-Computer cmdlet to create a new system
restore point.
PS > Get-ComputerRestorePoint | >> Select Description,SequenceNumber,RestorePointType | >> Format-Table -Auto >> Description SequenceNumber RestorePointType ----------- -------------- ---------------- Windows Update 122 0 Windows Update 123 0 Scheduled Checkpoint 124 7 Scheduled Checkpoint 125 7 Windows Update 126 0 Scheduled Checkpoint 127 7 Scheduled Checkpoint 128 7 Windows Update 129 0 Scheduled Checkpoint 130 7 Windows Update 131 0 Scheduled Checkpoint 132 7 Windows Update 133 0 Manual Checkpoint 134 0 Before driver updates 135 0 PS > Checkpoint-Computer "Before driver updates"
The computer restore point cmdlets give you an
easy way to manage Windows' system restore points. You can use the
Checkpoint-Computer to create a new restore point
before a potentially disruptive installation or system change. If you
need to restore the computer to a previous state, you can use the
Get-ComputerRestorePoint cmdlet to list existing
restore points, and then use the Restore-Computer
cmdlet to restore the computer to its previously saved state.
System restore points are finely tuned toward managing the state of the operating system, and are not designed to protect user data. System restore points primarily protect the Windows Registry, core operating system files, local user profiles, COM and WMI registration databases.
To conserve disk space, Windows limits the amount of space consumed by restore points, and removes the oldest restore points as needed. If you plan to create manual checkpoints more frequently than the ones automatically scheduled by Windows, consider increasing the amount of space dedicated to system restore points. If you don't, you run the risk of being unable to recover from system errors that took you a long time to detect.
Figure 27.1. Managing computer restore points

By default, Windows schedules automatic restore points for
your main system volume. To enable or disable these automatic
checkpoints for this (or any) volume, use the
Enable-ComputerRestore and
Disable-ComputerRestore cmdlets.
On Windows 7, the control panel lets you
configure how much space Windows reserves for restore points. To do
this, open the System control panel group, and
then open System Protection. On Windows Vista,
use the vssadmin.exe tool to manage this
policy.
Use the Restart-Computer
cmdlet to restart a computer:
PS > Restart-Computer -ComputerName ComputerUse the Stop-Computer cmdlet to shut it down entirely:
PS > Stop-Computer -ComputerName ComputerIf you want to perform the same action on many computers, use the cmdlet's throttling support:
PS > $computers = Get-Content computers.txt PS > Restart-Computer -ComputerName $computers -ThrottleLimit
Both the Restart-Computer
and Stop-Computer cmdlets let you manage the reboot
and shutdown process of a local or remote computer. Since they build on
PowerShell's WMI support, they also offer the
-ThrottleLimit parameter to let you control how many
machines should be controlled at a time.
the -ThrottleLimit parameter parameter --> the -ThrottleLimit parameter
By default, these cmdlets reject a restart or
a shutdown if a user is logged on to the computer. To restart the
computer anyways, use the -Force parameter to
override this behavior.
parameter to to override --> parameter to override
While restarting a computer, you might sometimes want to have
the computer take some action after comes back online. To do this,
create a new scheduled task (using the
schtasks.exe application) with
ONSTART as the value of its schedule
(/SC) parameter. For more information, see the section called “Manage Scheduled Tasks on a Computer”.
Rather than shutdown or restart a computer, you might instead
want to suspend or hibernate it. While neither the
Restart-Computer nor Stop-Computer
cmdlets support this, you can use the
System.Windows.Forms.Application class from the .NET
Framework to do so:
Add-Type -Assembly System.Windows.Forms
[System.Windows.Forms.Application]::SetSuspendState("Suspend", $false, $false)
Add-Type -Assembly System.Windows.Forms
[System.Windows.Forms.Application]::SetSuspendState("Hibernate", $false, $false)This technique does not let you suspend or hibernate remote computers, but you can use PowerShell Remoting to invoke those commands on remote systems.
For more information about PowerShell Remoting, see Chapter 29, Remoting.
You want to determine whether a specific hotfix is installed on a system.
To retrieve a list of hotfixes applied to the
system, use the Get-Hotfix cmdlet:
PS > Get-HotFix KB968930 | Format-List Description : Windows Management Framework Core FixComments : Update HotFixID : KB968930 InstallDate : InstalledBy : XPMUser InstalledOn : Name : ServicePackInEffect : SP10 Status :
To search by description, use the
-Description parameter:
PS > Get-HotFix -Description *Framework* | Format-List Description : Windows Management Framework Core FixComments : Update HotFixID : KB968930 InstallDate : InstalledBy : XPMUser InstalledOn : Name : ServicePackInEffect : SP10 Status :
The Get-Hotfix cmdlet lets
you determine whether a hotfix is installed on a specific system. By
default, it retrieves hotfixes from the local system, but you can use
the -ComputerName parameter to retrieve hotfix
information from a remote system.
To manage scheduled tasks, use the schtasks.exe application.
To view the list of scheduled tasks:
PS > schtasks
TaskName Next Run Time Status
==================================== ======================== =============
Defrag C 03:00:00, 5/21/2007
User_Feed_Synchronization-{CA4D6D9C- 18:34:00, 5/20/2007
User_Feed_Synchronization-{CA4D6D9C- 18:34:00, 5/20/2007To schedule a task to defragment C: every day at 3:00 a.m.:
schtasks /create /tn "Defrag C" /sc DAILY `
/st 03:00:00 /tr "defrag c:" /ru AdministratorTo remove a scheduled task by name:
schtasks /delete /tn "Defrag C"
The example in the solution tells the system
to defragment C: every day at 3:00 a.m. It runs
this command under the Administrator
account, since the defrag.exe command
requires administrative privileges. In addition to scheduling tasks on
the local computer, the schtasks.exe
application also allows you to schedule tasks on remote
computers.
On Windows Vista, the schtasks.exe application has been enhanced to
support event triggers, conditions, and additional settings.
While the schtasks.exe application doesn't
support PowerShell scripts directly, you can always use PowerShell's
command-line parameters to launch a script of your choice. For
example:
powershell -noprofile -noexit -windowstyle hidden -file e:\lee\tools\Start-Scheduler.ps1
For more information about automating PowerShell from other applications, see the section called “Invoke a PowerShell Command or Script From Outside PowerShell”.
For more information about the schtasks.exe
application, type schtasks
/?.
You want to get information about printers on the current system.
To retrieve information about printers
attached to the system, use the Win32_Printer WMI class:
PS > Get-WmiObject Win32_Printer | Select-Object Name,PrinterStatus Name PrinterStatus ---- ------------- Microsoft Office Document Image Wr... 3 Microsoft Office Document Image Wr... 3 CutePDF Writer 3 Brother DCP-1000 3
To retrieve information about a specific printer, apply a filter based on its name:
PS > $device = Get-WmiObject Win32_Printer -Filter "Name='Brother DCP-1000'"
PS > $device | Format-List *
Status : Unknown
Name : Brother DCP-1000
Attributes : 588
Availability :
AvailableJobSheets :
AveragePagesPerMinute : 0
Capabilities : {4, 2, 5}
CapabilityDescriptions : {Copies, Color, Collate}
Caption : Brother DCP-1000
(...)To retrieve specific properties, access as you would access properties on other PowerShell objects:
PS > $device.VerticalResolution 600 PS > $device.HorizontalResolution 600
The example in the solution uses the Win32_Printer WMI class to retrieve
information about installed printers on the computer. While the Win32_Printer class gives access to most
commonly used information, WMI supports several other printer-related
classes: Win32_TCPIPPrinterPort,
Win32_PrinterDriver, CIM_Printer, Win32_PrinterConfiguration,
Win32_PrinterSetting, Win32_PrinterController,
Win32_PrinterShare, and Win32_PrinterDriverDll. For more information
about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
You want to get information about print queues for printers on the current system.
To retrieve information about printers
attached to the system, use the Win32_PerfFormattedData_Spooler_PrintQueue WMI
class:
PS > Get-WmiObject Win32_PerfFormattedData_Spooler_PrintQueue | >> Select Name,TotalJobsPrinted >> Name TotalJobsPrinted ---- ---------------- Microsoft Office Document Image Wr... 0 Microsoft Office Document Image Wr... 0 CutePDF Writer 0 Brother DCP-1000 2 _Total 2
To retrieve information about a specific printer, apply a filter based on its name, as shown in Example 27.4, “Retrieving information about a specific printer”.
Example 27.4. Retrieving information about a specific printer
PS > $queueClass = "Win32_PerfFormattedData_Spooler_PrintQueue" PS > $filter = "Name='Brother DCP-1000'" PS > $stats = Get-WmiObject $queueClass -Filter $filter PS > $stats | Format-List * AddNetworkPrinterCalls : 129 BytesPrintedPersec : 0 Caption : Description : EnumerateNetworkPrinterCalls : 0 Frequency_Object : Frequency_PerfTime : Frequency_Sys100NS : JobErrors : 0 Jobs : 0 JobsSpooling : 0 MaxJobsSpooling : 1 MaxReferences : 3 Name : Brother DCP-1000 NotReadyErrors : 0 OutofPaperErrors : 0 References : 2 Timestamp_Object : Timestamp_PerfTime : Timestamp_Sys100NS : TotalJobsPrinted : 2 TotalPagesPrinted : 0
To retrieve specific properties, access as you would access properties on other PowerShell objects:
PS > $stats.TotalJobsPrinted 2
The Win32_PerfFormattedData_Spooler_PrintQueue WMI
class provides access to the various Windows performance counters
associated with print queues. Because of this, you can also access them
through the .NET Framework, as mentioned in the section called “Access Windows Performance Counters”:
PS > Get-Counter "\Print Queue($printer)\Jobs" | Select -Expand CounterSamples | >> Select InstanceName,CookedValue | Format-Table -Auto >> InstanceName CookedValue ------------ ----------- brother dcp-1000 usb 1
For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
To manage printers attached to the system, use
the Win32_Printer WMI class. By
default, the WMI class lists all printers:
PS > Get-WmiObject Win32_Printer | Select-Object Name,PrinterStatus Name PrinterStatus ---- ------------- Microsoft Office Document Image Wr... 3 Microsoft Office Document Image Wr... 3 CutePDF Writer 3 Brother DCP-1000 3
To clear the print queue of a specific
printer, apply a filter based on its name and call the CancelAllJobs() method:
PS > $device = Get-WmiObject Win32_Printer -Filter "Name='Brother DCP-1000'"
PS > $device.CancelAllJobs()
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 5The example in the solution uses the Win32_Printer WMI class to cancel all jobs for
a printer. In addition to cancelling all print jobs, the Win32_Printer class supports other
tasks:
PS > $device | Get-Member -MemberType Method TypeName: System.Management.ManagementObject#root\cimv2\Win32_Printer Name MemberType Definition ---- ---------- ---------- CancelAllJobs Method System.Management.ManagementBaseObject Can... Pause Method System.Management.ManagementBaseObject Pau... PrintTestPage Method System.Management.ManagementBaseObject Pri... RenamePrinter Method System.Management.ManagementBaseObject Ren... Reset Method System.Management.ManagementBaseObject Res... Resume Method System.Management.ManagementBaseObject Res... SetDefaultPrinter Method System.Management.ManagementBaseObject Set... SetPowerState Method System.Management.ManagementBaseObject Set...
For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
WMI provides an immense amount of information
about the current system or remote systems. In fact, the msinfo32.exe application traditionally used to
gather system information is based largely on WMI.
The script shown in Example 27.5, “Get-DetailedSystemInformation.ps1” summarizes the most common information, but WMI provides a great deal more than that. For a list of other commonly used WMI classes, see Appendix G, WMI Reference. For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
Example 27.5. Get-DetailedSystemInformation.ps1
############################################################################## param( $computer = "." ) "#"*80 "System Information Summary" "Generated $(Get-Date)" "#"*80 "" "" "#"*80 "Computer System Information" "#"*80 Get-WmiObject Win32_ComputerSystem -Computer $computer | Format-List * "#"*80 "Operating System Information" "#"*80 Get-WmiObject Win32_OperatingSystem -Computer $computer | Format-List * "#"*80 "BIOS Information" "#"*80 Get-WmiObject Win32_Bios -Computer $computer | Format-List * "#"*80 "Memory Information" "#"*80 Get-WmiObject Win32_PhysicalMemory -Computer $computer | Format-List * "#"*80 "Physical Disk Information" "#"*80 Get-WmiObject Win32_DiskDrive -Computer $computer | Format-List * "#"*80 "Logical Disk Information" "#"*80 Get-WmiObject Win32_LogicalDisk -Computer $computer | Format-List *
For more information about running scripts, see the section called “Run Programs, Scripts, and Existing Tools”.
You want to renew the DHCP lease for a connection on a computer.
To renew DHCP leases, use the ipconfig application. To renew the lease on
all connections:
PS > ipconfig /renew
To renew the lease on a specific connection:
PS > ipconfig /renew "Wireless Network Connection 4"
The standard ipconfig application works well to manage
network configuration options on a local machine. To renew the lease on
a remote computer, you have two options.
To renew the lease on a remote computer, use
the Win32_NetworkAdapterConfiguration WMI class.
The WMI class requires that you know the description of the network
adapter, so first obtain that by reviewing the output of Get-WmiObject Win32_NetworkAdapterConfiguration
-Computer
<ComputerName>:
PS > Get-WmiObject Win32_NetworkAdapterConfiguration -Computer LEE-DESK
(...)
DHCPEnabled : True
IPAddress : {192.168.1.100}
DefaultIPGateway : {192.168.1.1}
DNSDomain : hsd1.wa.comcast.net.
ServiceName : USB_RNDIS
Description : Linksys Wireless-G USB Network Adapter with (...)
Index : 13
(...)Knowing which adapter you want to renew,
call its RenewDHCPLease()
method:
$description = "Linksys Wireless-G USB"
$adapter = Get-WmiObject Win32_NetworkAdapterConfiguration -Computer LEE-DESK |
Where-Object { $_.Description -match $description}
$adapter.RenewDHCPLease()Another way to renew the DHCP lease on a remote computer is to use either PowerShell Remoting, or the solution offered by the section called “Program: Invoke a PowerShell Expression on a Remote Machine”:
PS > Invoke-Command LEE-DESK { ipconfig /renew }
PS > Invoke-RemoteExpression \\LEE-DESK { ipconfig /renew }For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
Use the Win32_NetworkAdapterConfiguration WMI class to
manage network settings for a computer:
$description = "Linksys Wireless-G USB"
$staticIp = "192.168.1.100"
$subnetMask = "255.255.255.0"
$gateway = "192.168.1.1"
$adapter = Get-WmiObject Win32_NetworkAdapterConfiguration -Computer LEE-DESK |
Where-Object { $_.Description -match $description}
$adapter.EnableStatic($staticIp, $subnetMask)
$adapter.SetGateways($gateway, [UInt16] 1)When managing network settings for a computer,
the Win32_NetworkAdapterConfiguration
WMI class requires that you know the description of the network adapter.
Obtain that by reviewing the output of Get-WmiObject Win32_NetworkAdapterConfiguration
-Computer
<ComputerName>:
the Win32_NetworkAdapter Configuration --> the Win32_NetworkAdapterConfiguration
PS > Get-WmiObject Win32_NetworkAdapterConfiguration -Computer LEE-DESK
(...)
DHCPEnabled : True
IPAddress : {192.168.1.100}
DefaultIPGateway : {192.168.1.1}
DNSDomain : hsd1.wa.comcast.net.
ServiceName : USB_RNDIS
Description : Linksys Wireless-G USB Network Adapter with (...)
Index : 13
(...)Knowing which adapter you want to renew, you
can now call methods on that object as illustrated in the solution. To
enable DHCP on an adapter again, use the EnableDHCP() method:
PS > $adapter.EnableDHCP()
For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
To list IP addresses assigned to a computer,
use the ipconfig application:
PS > ipconfig
The standard ipconfig application works well to manage
network configuration options on a local machine. To view IP addresses
on a remote computer, you have two options.
To view IP addresses a remote computer, use
the Win32_NetworkAdapterConfiguration WMI class.
Since that lists all network adapters, use the Where-Object cmdlet to restrict the results
to those with an IP address assigned to them:
PS > Get-WmiObject Win32_NetworkAdapterConfiguration -Computer LEE-DESK |
>> Where-Object { $_.IpEnabled }
>>
DHCPEnabled : True
IPAddress : {192.168.1.100}
DefaultIPGateway : {192.168.1.1}
DNSDomain : hsd1.wa.comcast.net.
ServiceName : USB_RNDIS
Description : Linksys Wireless-G USB Network Adapter with SpeedBooste
r v2 - Packet Scheduler Miniport
Index : 13Another way to view the IP addresses of a remote computer is to use either PowerShell Remoting, or the solution offered by the section called “Program: Invoke a PowerShell Expression on a Remote Machine”:
PS > Invoke-Command LEE-DESK { ipconfig }
PS > Invoke-RemoteExpression \\LEE-DESK { ipconfig }For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
You want to retrieve information about network adapters on a computer.
To retrieve information about network adapters
on a computer, use the Win32_NetworkAdapterConfiguration WMI
class:
Get-WmiObject Win32_NetworkAdapterConfiguration -Computer <ComputerName>To list only those with IP addresses assigned
to them, use the Where-Object cmdlet
to filter on the IpEnabled
property:
PS > Get-WmiObject Win32_NetworkAdapterConfiguration -Computer LEE-DESK |
>> Where-Object { $_.IpEnabled }
>>
DHCPEnabled : True
IPAddress : {192.168.1.100}
DefaultIPGateway : {192.168.1.1}
DNSDomain : hsd1.wa.comcast.net.
ServiceName : USB_RNDIS
Description : Linksys Wireless-G USB Network Adapter with SpeedBooste
r v2 - Packet Scheduler Miniport
Index : 13The solution uses the Win32_NetworkAdapterConfiguration WMI class to
retrieve information about network adapters on a given system. By
default, PowerShell displays only the most important information about
the network adapter but provides access to much more.
To see all information available, use the
Format-List cmdlet, as shown in Example 27.6, “Using the Format-List cmdlet to see detailed information about
a network adapter”.
Example 27.6. Using the Format-List cmdlet to see detailed information about a network adapter
PS > $adapter = Get-WmiObject Win32_NetworkAdapterConfiguration |
>> Where-Object { $_.IpEnabled }
>>
PS > $adapter
DHCPEnabled : True
IPAddress : {192.168.1.100}
DefaultIPGateway : {192.168.1.1}
DNSDomain : hsd1.wa.comcast.net.
ServiceName : USB_RNDIS
Description : Linksys Wireless-G USB Network Adapter with SpeedBooste
r v2 - Packet Scheduler Miniport
Index : 13
PS > $adapter | Format-List *
DHCPLeaseExpires : 20070521221927.000000-420
Index : 13
Description : Linksys Wireless-G USB Network Adapter with
SpeedBooster v2 - Packet Scheduler Minipor
t
DHCPEnabled : True
DHCPLeaseObtained : 20070520221927.000000-420
DHCPServer : 192.168.1.1
DNSDomain : hsd1.wa.comcast.net.
DNSDomainSuffixSearchOrder :
DNSEnabledForWINSResolution : False
DNSHostName : Lee-Desk
DNSServerSearchOrder : {68.87.69.146, 68.87.85.98}
DomainDNSRegistrationEnabled : False
FullDNSRegistrationEnabled : True
IPAddress : {192.168.1.100}
IPConnectionMetric : 25
IPEnabled : True
IPFilterSecurityEnabled : False
WINSEnableLMHostsLookup : True
(...)To retrieve specific properties, access as you would access properties on other PowerShell objects:
PS > $adapter.MacAddress 00:12:17:77:B4:EB
For more information about working with WMI in PowerShell, see the section called “Access Windows Management Instrumentation Data”.
the section called “Access Windows Management Instrumentation Data”
Recipes that I would personally look for in this section: - How do I find out whether a computer dropped of the domain? - How do I reboot my local computer and resume the PowerShell script that triggered the reboot just where it was after the restart.
Another cool recipe would be about how to enable Remote Desktop on the remote computer using PowerShell.
Thanks, Klaus. I think the 'dropped off the domain' recipe is a little specific, but I've added a note about resumption after a reboot to the Restart-Computer recipe, and to the Scheduled Tasks recipe.
About the Remote Desktop -- great idea. I've added a short recipe to the Remoting chapter, with pointers to the Remote Registry recipe. I've also updated the Remote Registry recipe to show how to do it via WMI rather than .NET or PowerShell Remoting.
No comments yet
Add a comment