CODEDIGEST
Home » Tutorials
Search
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Windows PowerShell Cmdlet Tutorials with Example(contd..)
Author: balamurali balaji

This tutorial is brought to you by BB Systems.

Windows PowerShell Cmdlet Tutorials with Example[Contd...]


Previous||Next

Write-Host

 

This cmdlet displays objects by using the host user interface. Write-Host creates a customized host window. You can specify the color of text in that windows by using the ForegroundColor parameter and you can specify the background color of the window by using the BackgroundColor parameter. The Separator parameter lets you specify a string to use to separate displayed objects.

 

The -object parameter lists Objects to be displayed in the console.

The -foregroundcolor and -backgroundcolor parameters specifies the text and background color.

The -noNewLine parameter specifies that the content displayed in the console does not end with a newline character. The -separator specify the string to output between objects displayed on the console.

 

 

Examples

 

The command displays the input to the console, but because of the nonewline parameter, the output is followed directly by the prompt. Next command, adds the newline after the output.

 

PS D:\Users\bala> write-host "no newline specified here" -nonewline

no newline specified herePS D:\Users\bala>write-host "by default, newline is added"

by default, newline is added

PS D:\Users\bala>

 

This command displays the even numbers from 2 through 12. The Separator parameter is used to add the string ,".."

 

PS D:\Users\bala> write-host (2,4,6,8,10,12) -separator ".."

2..4..6..8..10..12

 

This command displays the text. It uses the Foregroundcolor parameter to output green text and the Backgroundcolor parameter to display a white background.

 

PS D:\Users\bala> write-host "by default, newline is added" -foregroundcolor Green -backgroundcolor white

by default, newline is added

 

Write-Error

 

This cmdlet is used to write an object to the error pipeline. Lets you write error messages along with other information such as an id, object data, and suggested actions.

 

The -message parameter specifies the message text of the error.

 

The -category parameter specifies the category of the error.

The -errorId and  -targetObject parameters specify the id of the associated error and the object with which the error is associated.

 

The -recommendedAction parameter sescribes the recommended response to the error.

 

The -exception specifies the exception type of the error. This parameter can be used in place of Message and ErrorRecord, in which case it should appear as the first parameter of the parameter set.

 

The -errorRecord specifies an error record describing details about the error. This parameter can be used in place of the Exception and Message parameters, in which case it is the first parameter of the parameter set.

 

Examples

 

This command writes an object to the error pipeline if the Get-ChildItem cmdlet returns an object of type Microsoft.Win32.Registry, which it will do if the command is run within the namespace of the Registry provider.

 

PS D:\Users\bala> get-childitem | foreach-object { if ($_.gettype().tostring() -eq "Videos") {write-error "out of" -errorid b1 -targetobject $_ } else {$_} }

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d-r--        23-11-2007  13:25:13            Contacts

d-r--        02-02-2008  23:29:43            Desktop

d-r--        11-02-2008  12:56:33            Documents

d-r--        10-02-2008  14:27:58            Downloads

d-r--        04-02-2008  19:10:07            Favorites

d-r--        17-01-2008  16:50:44            Links

 

Now, run the same command in the Registry mode and you will get error.

 

Write-Warning

 

This cmdlet writes a warning message. The message is sent directly to the host. Whether the message is displayed in the console depends upon the value of the $WarningPreference variable. Type $WarningPreference to see its current value. To set the variable for the session, type $WarningPreference = "<value>". The valid values are: SilentlyContinue, Stop, Continue and Inquire. If the value is SilentlyContinue, Write-Warning does not display a message to the console. When the message is displayed, reverse video is used to highlight it.

 

The -message parameter specifies the warning message.

 

Examples:

 

This command displays a warning message specified in the quotes.

 

PS D:\Users\bala> write-warning "Please do not skip this content"

WARNING: Please do not skip this content

 

The following command set the value "stop" to the $WarningPreference variable.

PS D:\Users\bala> $WarningPreference = "Stop"

 

The following command checks the effect of "stop"

 

PS D:\Users\bala> write-warning "Please do not skip this content"

WARNING: Please do not skip this content

Write-Warning : Command execution stopped because the shell variable "WarningPreference" is set to Stop.

At line:1 char:14 + write-warning  <<<< "Please do not skip this content"

 

Note that the command execution is stopped after displaying the warning message.

 

 

 

 

Write-Debug

 

This cmdlet writes debug messages to the console from a script or command. Whether the message is displayed in the console depends upon the value of the $DebugPreference variable.

 

Type $DebugPreference to see its current value. To set the variable for the session, type $DebugPreference  = "<value>". The valid values are: SilentlyContinue, Stop, Continue and Inquire. If the value is SilentlyContinue, Write-Debug does not display a message to the console.

 

The parameter -message specifies the debug message to send to the console.

 

 

Examples:

 

This command writes a debug message which will be shown or not depending upon the value of $DebugPreference. The value "SilentlyContinue" means do not show the statement.  The Value "Continue" means show the value.

 

 

PS D:\Users\bala> write-debug "This script performed some malfunction"

PS D:\Users\bala> $debugpreference="continue"

PS D:\Users\bala> write-debug "This script performed some malfunction"

DEBUG: This script performed some malfunction

PS D:\Users\bala> $debugpreference="silentlycontinue"

PS D:\Users\bala> write-debug "This script performed some malfunction"

PS D:\Users\bala>

 

 

Write-Verbose

 

This cmdlet writes a string to the verbose display of the host. The value of the $VerbosePreference variable determines whether or not the string is displayed in the console window.

 

To see the value of the variable, type $VerbosePreference. Valid values are: SilentlyContinue, Stop, Continue and Inquire. To set the value of the variable in the current session, type $VerbosePreference = "<value>". If $VerbosePreference is set to SilentlyContinue, running Write-Verbose does not display anything to the console. 

 

The -message parameter specifies the message to display.

 

Examples

 

This command sets the $verbosepreference variable to SilentlyContinue. It then uses the Write-Verbose cmdlet to display the message "Hi Welcome". Nothing is displayed because of the value of the $verbosepreference variable. The $verbosepreference variable value is then changed to Continue and the next call to Write-Verbose displays the message as a result.

 

PS D:\Users\bala> write-verbose "Hi, welcome"

PS D:\Users\bala> $verbosepreference

SilentlyContinue

PS D:\Users\bala> $verbosepreference="continue"

PS D:\Users\bala> write-verbose "Hi, welcome"

VERBOSE: Hi, welcome

 

 

The following command shows how to set the value "inquire" to the verbosepreference value. It prompts for the user confirmation.

 

PS D:\Users\bala> $verbosepreference="inquire"

PS D:\Users\bala> write-verbose "Hi, welcome"

VERBOSE: Hi, welcome

 

Confirm

Continue with this operation?

[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): Y

 

Write-Progress

 

The Write-Progress cmdlet displays a progress bar within a Windows PowerShell command window. Whether the progress bar is displayed is controlled by the $ProgressPreference variable.

 

To see the value of that variable, type $ProgressPreference. Valid values for the variable are: SilentlyContinue, Continue, Stop and Inquire. If the value is set to SilentlyContinue, no progress information is displayed in the console.

 

To set the value of variable for the session, type $ProgressPreference = "<value>". Write-Progress can use data about the state of a running command or script to provide a visual indication of progress within the console window.

 

The parameter -activity specifies a string that describes the activity about which progress is being reported. The -status parameter specifies a string that describes current state of the activity about which progress is being reported. The -id parameter specifies the activity identifier for this progress record. -percentComplete specifies the percentage of the activity that is completed.

 

Examples:

 

The following command displays progress of a for loop.

 

PS D:\Users\bala> for ($i=1;$i -lt 101; $i++) { for ($j=0; $j -lt 10000; $j++) {} write-progress "Numbers on the run..."

 "Completed %: " -perc $i; }

 

Numbers on the run...

      Completed %:

      [oooooooooooooooooo                                                       ]

 

Typing the variable, you get the status.

 

PS D:\Users\bala> $ProgressPreference

Continue

 

 

Write-Output

 

This cmdlet Writes objects to the success pipeline. echo is the alias for this cmdlet.

 

The inputobject parameter specifies the objects to send along the pipeline. Enter a variable that contains the objects or type a command or expression that gets the objects.

 

Examples

 

This command pipes the string "Balamurali Balaji" to the Get-Member cmdlet which displays the members of the String class, demonstrating that the string was passed along the pipeline.

 

PS D:\Users\bala> write-output "Balamurali Balaji" | get-member

 

   TypeName: System.String

 

Name             MemberType            Definition

----             ----------            ----------

Clone            Method                System.Object Clone()

CompareTo        Method                System.Int32 CompareTo(Object value), System.Int32 CompareTo(String strB)

Contains         Method                System.Boolean Contains(String value)

CopyTo           Method                System.Void CopyTo(Int32 sourceIndex, Char[] destination, Int32 destinationIn...

........

........

 

The following commands define a variable and echo cmdlet is used to list all the members of an integer type, since 200 is an integer.

 

PS D:\Users\bala> $myvariable = 200

PS D:\Users\bala> echo $myvariable

200

PS D:\Users\bala> echo $myvariable  | get-member

 

   TypeName: System.Int32

 

Name        MemberType Definition

----        ---------- ----------

CompareTo   Method     System.Int32 CompareTo(Int32 value), System.Int32 CompareTo(Object value)

Equals      Method     System.Boolean Equals(Object obj), System.Boolean Equals(Int32 obj)

GetHashCode Method     System.Int32 GetHashCode()

GetType     Method     System.Type GetType()

GetTypeCode Method     System.TypeCode GetTypeCode()

ToString    Method     System.String ToString(), System.String ToString(IFormatProvider provider), System.String ToS...

 

 

Measure-Object

 

This cmdlet measures characteristics of objects and their properties, mostly the objects with textual properties. There are three distinct actions that the cmdlet can perform. The type of measurement action that takes place depends upon the parameters specified.

 

If you do not specify any parameters, the cmdlet returns a count of the number of input objects.

 

If the Property parameter is specified along with either the Sum or Average parameter, the sum or average of the properties is calculated. Textual properties are measured when one or more of the  Line, Word, or Character, parameters is specified.

 

The -inputObject parameter specifies the objects to be measured. Enter a variable that contains the objects or type a command or expression that gets the objects.

 

Examples

 

This command displays the number of files and folders in the current directory. (requires that the current location is a drive mapped to the FileSystem provider)

 

PS D:\Users\bala> get-childitem | measure-object

 

Count    : 15

Average  :

Sum      :

Maximum  :

Minimum  :

Property :

 

This command displays the minimum, maximum and sum of the sizes of all files in the current directory as well as the average size of a file in the directory.

 

PS D:\Users\bala> get-childitem | measure-object -property length -minimum -maximum -average

 

Count    : 3

Average  : 5327.33333333333

Sum      :

Maximum  : 15260

Minimum  : 272

Property : length

 

This command displays the number of characters, words and lines in the text.txt file.

 

PS D:\Users\bala> get-content bb.txt | measure-object -character -line -word

 

                        Lines                         Words                    Characters Property

                        -----                           -----                      ----------   --------

                           63                           500                          7497

 

 

Start-Transcript

 

The Start-Transcript cmdlet creates a record of all or part of a Windows PowerShell session in a text file. The transcript includes all command that the user types and all output that appears on the console.

 

The -path parameter specifies a location for the transcript file with .txt extension. If you do not specify a path, Start-Transcript uses the path in the value of the $Transcript global variable.

The -noClobber parameter will not overwrite (replace the contents) of an existing file. By default, if a transcript file exists in the specified path, Start-Transcript overwrites the file without warning.

 

To end the recording of cmdlets being executed, issue a stop-transcript cmdlet. Accessing the transcript file with out stopping the recording would loop around the console output.

 

Examples

 

This command starts a transcript in the cmdlist.txt file in documents subfolder in the current directory. The NoClobber parameter prevents any existing files from being overwritten. If the cmdlist.txt file already exists, the command fails.

 

PS D:\Users\bala> start-transcript documents\cmdlist.txt

Transcript started, output file is documents\cmdlist.txt

PS D:\Users\bala> get-date

 

30 January 2008 17:24:45

 

PS D:\Users\bala> get-childitem

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

Mode                LastWriteTime     Length   Name

----                -------------                 ------    ----

d-r--        17-01-2008  16:50:44                   Links

d----        17-03-2008  17:31:43                   newfolder

-a---        12-03-2008  10:38:52      15260 bb.txt

-a---        16-03-2008  11:15:43        450    events.txt

-a---        08-03-2008  11:18:01        272    myevents.txt

 

 

PS D:\Users\bala> stop-transcript

Transcript stopped, output file is D:\Users\bala\documents\cmdlist.txt

 

 

PS D:\Users\bala> type documents\cmdlist.txt

**********************

Windows PowerShell Transcript Start

Start time: 20080130172433

Username  : balamurali-b\bala

Machine   : BALAMURALI-B (Microsoft Windows NT 6.0.6000.0)

**********************

Transcript started, output file is documents\cmdlist.txt

PS D:\Users\bala> get-date

 

**********************

Windows PowerShell Transcript End

End time: 20080130172502

**********************

 

 

 

Start-Sleep

 

The Start-Sleep cmdlet suspends shell, script, or runspace activity for the specified period of time. You can use it in a script to wait for an operation to complete, or in a loop, to wait a specific time before repeating an operation.

 

The -seconds and -milliseconds parameter specifies how long the resource sleeps in miiliseconds respectively.

 

Examples

 

This command makes the shell sleep for 5 seconds.

 

PS D:\Users\bala> start-sleep 5

 

This command makes the command shell sleep for 5 seconds (5000 milliseconds).

 

PS D:\Users\bala> start-sleep -m 5000

 

 

 

New-TimeSpan

 

It creates a TimeSpan object. The resulting object can be used to add or subtract time from a DateTime object to create additional DateTime objects.

 

The -start parameter indicates the start of a timespan and -end parameter indicates the end of a timespan. The -days,  -hours, -minutes,  -seconds parameters are also available.

 

Examples

 

This command creates a TimeSpan object of duration 1 hour and 25 minutes and stores it in a variable named $timespan. It displays a representation of the TimeSpan object.

 

PS D:\Users\bala> $timenow = new-timespan -hour 5 -minute 30

PS D:\Users\bala> $timenow

 

Days                : 0

Hours               : 5

Minutes            : 30

Seconds           : 0

Milliseconds      : 0

Ticks                : 198000000000

TotalDays         : 0.229166666666667

TotalHours        : 5.5

TotalMinutes      : 330

TotalSeconds      : 19800

TotalMilliseconds : 19800000

 

This example creates a new TimeSpan object that represents the duration between when the command is run and May 27, 1970.

 

PS D:\Users\bala> $sometime = new-timespan (get-date 1970 -month 05 -day 29)

PS D:\Users\bala> $sometime

 

Days               : 732922

Hours              : 10

Minutes           : 48

Seconds           : 8

Milliseconds      : 187

Ticks                : 633244996881876130

TotalDays          : 732922.450094764

TotalHours         : 17590138.8022743

TotalMinutes       : 1055408328.13646

TotalSeconds      : 63324499688.1876

TotalMilliseconds : 63324499688187.6

 

 

 

 

 

Get-Credential

 

The Get-Credential cmdlet creates a credential object for a specified username and password. Later, you can use the credential object in security operations.

 

The -credential parameter is optional and it specifies a user name for the credential, such as "User01" or "Domain01\User01". When you enter the command, you will be prompted for a password. If you omit this parameter, you will be prompted for a user name and a password.

 

Examples:

 

This command gets a credential object and saves it in the $logininfo variable.

 

PS D:\Users\bala> $logininfo = get-credential

 

cmdlet get-credential at command pipeline position 1

Supply values for the following parameters:

Credential   

 

When you enter the command, a dialog box appears requesting a user name and password. When you enter the requested information, the cmdlet creates a PSCredential object representing the credentials of the user and saves it in the $logininfo variable.

 

You can use the object as input to cmdlets that request user authentication, such as those with a Credential parameter. However, the providers that are installed currently with Windows PowerShell do not support the Credential parameter.

 

 

This command uses a credential object from Get-Credential to authenticate a user on a remote computer so they can use Windows Management Instrumentation (WMI) to manage the computer.

 

PS D:\Users\bala> get-wmiobject win32-diskdrive -computername bala -credential $logininfo

 

Note: Credential parameter in PowerShell commands work only for remote computers within a network; not with the local computer.

 

 

Format-Custom

 

The Format-Custom cmdlet formats the output of a command as defined in an alternate view. Format-Custom is designed to display views that are not just tables or just lists. You can use the views defined in the *format.PS1XML files  in the Windows PowerShell directory or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to add them to Windows PowerShell.

 

The -property parameter specifies the object properties that appear in the display and the order in which they appear.

The -inputObject specifies the objects to be formatted. Enter a variable that contains the objects or type a command or expression that gets the objects.

 

The -view parameter specifies the name of an alternate format or "view." If you omit this parameter, Format-Custom uses a default custom view. You cannot use the Property and View parameters in the same command.

 

Examples

 

This command formats information about the Winlogon process in an alternate customized view. Because the command does not use the View parameter, Format-Custom uses a default custom view to format the data.

 

PS D:\Users\bala> get-process winlogon | format-custom

 

class Process

{

  Id = 740

  Handles = 125

  CPU =

  Name = winlogon

}

 

This command formats information about the get-alias in an alternate customized view.

 

PS D:\Users\bala> get-alias | format-custom

 

class AliasInfo

{

  ResolvedCommandName = Add-Content

  ReferencedCommand =

    class CmdletInfo

    {

      DLL= :\Windows\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Management \1.0.0.0__31bf3856ad364e35\Microsoft.PowerShell.Commands.Management.dll

      Verb = Add

 

      Noun = Content

...

...

...

 

Format-Wide

 

The Format-Wide cmdlet formats objects as a wide table that displays only one property of each object. You can use the Property parameter to determine which property is displayed.

 

The parameter -property is optional and it specifies the object properties that appear in the display and the order in which they appear.

The -column specifies the number of columns in the display. You cannot use the Autosize and Column parameters in the same command.

 

The Alias for this cmdlet is fw.

 

Examples

 

This command displays the names of files in the current directory in three columns across the screen.

 

PS D:\Users\bala> get-childitem | format-wide -column 3

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

[Contacts]                              [Desktop]                               [Documents]

[Downloads]                             [Favorites]                             [Links]

[newfolder]                             [Pictures]                              [Saved Games]

[Searches]                              [Tracing]                               [Videos]

bb.txt                                  events.txt                              myevents.txt

 

The following cmdlet displays name of the files in the current directory in as many columns as required across the screen with the use of -autosize parameter.

 

PS D:\Users\bala> get-childitem | format-wide -autosize

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

[Contacts]     [Desktop]      [Documents]    [Downloads]    [Favorites]    [Links]        [newfolder]    [Pictures]

[Saved Games]  [Searches]     [Tracing]      [Videos]       bb.txt         events.txt     myevents.txt

 

 

 

 

Format-List

 

The Format-List cmdlet formats the output of a command as a list of properties in which each property is displayed on a separate line. Because more space is available for each item in a list than in a table, Windows PowerShell displays more properties of the object in the list, and the property values are less likely to be truncated. You can use a command to format all properties of an object as a list (format-list *) to find all of the properties of the object.

 

The -property, an optional parameter specifies the object properties that appear in the display and the order in which they appear. The   -view specifies the name of an alternate list format or "view." You cannot use the Property and View parameters in the same command. The  -groupBy parameter formats the output in groups based on a shared property or value. Enter an expression or a property of the output.

 

The Alias for this cmdlet is fl.

 

Examples:

 

This command formats information about processes running on the computer as a list. By default, the services are formatted as a table.

 

 

PS D:\Users\bala> get-process | format-list

 

Id      : 1128

Handles : 108

CPU     :

Name    : audiodg

 

Id      : 940

Handles : 154

CPU     :

Name    : avgamsvr

 

Id      : 1284

Handles : 187

CPU     : 6.71875

Name    : avgcc

 

These commands display information about files in the Windows PowerShell directory as a list.

 

PS D:\Users\bala> get-childitem $pshome | format-list

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Windows\System32\WindowsPowerShell\v1.0

 

Name           : Documents

CreationTime   : 04-03-2008 11:14:44

LastWriteTime  : 04-03-2008 11:14:44

LastAccessTime : 04-03-2008 11:14:44

 

Name           : en-US

CreationTime   : 04-03-2008 11:14:42

LastWriteTime  : 04-03-2008 11:14:44

LastAccessTime : 04-03-2008 11:14:44

 

Name           : Examples

CreationTime   : 04-03-2008 11:14:44

LastWriteTime  : 04-03-2008 11:14:44

LastAccessTime : 04-03-2008 11:14:44

 

Name           : Certificate.format.ps1xml

Length         : 22120

CreationTime   : 04-03-2008 11:14:25

LastWriteTime  : 04-03-2008 11:14:25

LastAccessTime : 04-03-2008 11:14:25

VersionInfo    :

....

....

 

This command displays the Id and name of each process on the computer

 

PS D:\Users\bala> get-process | format-list -property id,name

 

Id   : 1128

Name : audiodg

 

Id   : 940

Name : avgamsvr

 

Id   : 1284

Name : avgcc

 

Id   : 2040

Name : avgemc

 

Id   : 456

Name : avgrssvc

....

....

 

 

 

 

 

 

 

 

New-Alias

 

This cmdlet creates a new alias. This alias name will be added to the list for the session. Aliases created by using New-Alias are not saved after you exit the session or close Windows PowerShell. You can use the Export-Alias cmdlet to save your alias information to a file. You can later use Import-Alias to retrieve that saved alias information.

 

The -name parameter specifies the new alias. The -value parameter specifies the name of the cmdlet or command element that is being aliased. You may include -description parameter to specify a description of the alias. You can type any string. If the description includes spaces, enclose it quotation marks. But this option will not work currently in v1.0 of PowerShell.

 

Examples:

 

This command creates an alias named 'list' to represent the Get-ChildItem cmdlet.

 

PS D:\Users\bala> new-alias list get-childitem

PS D:\Users\bala> list

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d-r--        23-11-2007  13:25:13            Contacts

d-r--        21-01-2008  17:02:44            Desktop

d-r--        20-01-2008  18:08:18            Documents

-a---        12-03-2008  10:38:52      15260 bb.txt

-a---        16-03-2008  11:15:43        450 events.txt

-a---        08-03-2008  11:18:01        272 myevents.txt

 

The following command creates the alias "list" once again with some description and -force parameter is used to over-write the existing alias.

 

PS D:\Users\bala> new-alias list -value 'get-childitem' -description "new alias to list all the files and folders" -force

PS D:\Users\bala> list

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

Mode                LastWriteTime     Length Name

----                -------------     ------ ----

----                -------------     ------ ----

d-r--        23-11-2007  13:25:13            Contacts

d-r--        21-01-2008  17:02:44            Desktop

d-r--        20-01-2008  18:08:18            Documents

-a---        12-03-2008  10:38:52      15260 bb.txt

-a---        16-03-2008  11:15:43        450 events.txt

-a---        08-03-2008  11:18:01        272 myevents.txt

 

 

 

Invoke-Item

 

This cmdlet invokes the provider-specific default action on the specified item. When applied to a file system item, for example, it will either run the file or open it with the application associated with that file type.

 

The parameter -path specifies the path to the item or file that is the object of the Cmdlet.

 

After changing the location to the specified folder, this command opens the file myevents.txt in Notepad.

 

PS D:\Windows\System32> set-location d:\users\bala

 

PS D:\users\bala> invoke-item myevents.txt

 

This command opens the file myevents.txt in Microsoft Word.

 

PS D:\users\bala> invoke-item documents\*.doc

 

 

Move-ItemProperty

 

This cmdlet is used to move a property of an item from one item to another item. For example, it can move a registry entry from one registry key to another.  When you move an item property, it is added to the new location and deleted from its original location.

 

 

The parameter -path specifies the path to the current location of the property and -destination specifies the path to the destination location. The parameter -name specifies the name of the property to be moved.

 

Examples:

 

This command moves the "username" registry value, and its data, from the Mycompany key to the google subkey of the HKLM\Software\MyCompany registry key.

 

PS HKLM:\software> move-itemproperty mycompany -name username -destination hklm:\software\google

 

 

 

Set-ItemProperty

 

This cmdlet sets the value of a property at the specified location. Works with many different properties in many different locations. "sp" is the alias for this cmdlet.

 

Include the -path to specify the path to the items with the property to be set. -inputObject parameter is used to specify the name of the properties to set.

 

Most of the properties are read-only and you need to be careful in using this cmdlet when you change the current value of properties to new values.

 

Examples:

 

This command sets the value of the username to "Ram" in the mycompany entry.

 

PS HKLM:\software> get-itemproperty mycompany

 

 

PSPath           : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany

PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software

PSChildName  : mycompany

PSDrive       : HKLM

PSProvider   : Microsoft.PowerShell.Core\Registry

config         : 1

username   : bala

 

Using get-itemproperty, you may view the property details including its value.

 

PS HKLM:\software> set-itemproperty mycompany -name username  -Value "Ram"

PS HKLM:\software> get-itemproperty mycompany

 

PSPath          : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany

PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software

PSChildName  : mycompany

PSDrive        : HKLM

PSProvider    : Microsoft.PowerShell.Core\Registry

config          : 1

username    : Ram

 

 

 

New-ItemProperty

 

This cmdlet sets a new property of an item at a location.

 

With the  -path parameter, the path of the item for which a new property is to be created.

 

The name and value of the property to be created is set using -name and -value parameters.

 

The -propertyType parameter is used to specify the Type of the property.

 

Examples:

 

Nowchange the location to registry and try out the following example. You must run the PowerShell command window as Administrator.

 

 

PS D:\Users\bala> set-location hklm:\software

 

This example assumes working in the Registry namespace where there is a store for a mycompany under "HKLM:\Software". Now, in the store there is a new int property named "Config".

 

PS HKLM:\software> new-itemproperty mycompany -name config -Value 1

 

PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany

PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software

PSChildName  : mycompany

PSDrive      : HKLM

PSProvider   : Microsoft.PowerShell.Core\Registry

config       : 1

 

You may view the property newly created, as below:

 

PS HKLM:\software> get-item my*

 

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software

 

SKC  VC Name                               Property

---    --  ----                                  --------

  0      1 Mycompany                      {config}

 

 

 

 

Format-Table

 

This cmdlet formats the output of a command as a table with a selected properties of the object in each column. The object type determines the default layout and properties that are displayed in each column, but you can use the Property parameter to select the properties that you want to see.

 

To add calculated properties to an object before displaying it. use the Property parameter to specify a hash table. The hash table must include two keys: Label and Expression.

 

The parameter -autosize adjusts the column size and number of columns based on the width of the data. The -hideTableHeaders parameter     omits the column headings from the table. -groupBy formats the output in groups based on a shared property or value. The -wrap parameter displays text that exceeds the column width on the next line.

 

Examples:

 

This command formats information about Windows PowerShell snap-ins in a table. By default, they are formatted in a list. The Autosize parameter adjusts the column widths to minimize truncation.

 

PS D:\Windows\System32> get-pssnapin  | format-table -auto

 

Name                                     PSVersion     Description

----                                        ---------      -----------

Microsoft.PowerShell.Core             1.0       This Windows PowerShell snap-in contains Windows PowerShell management cmd...

Microsoft.PowerShell.Host             1.0       This Windows PowerShell snap-in contains cmdlets used by the Windows Power...

Microsoft.PowerShell.Management 1.0       This Windows PowerShell snap-in contains management cmdlets used to manage...

Microsoft.PowerShell.Security         1.0       This Windows PowerShell snap-in contains cmdlets to manage Windows PowerSh...

Microsoft.PowerShell.Utility            1.0       This Windows PowerShell snap-in contains utility Cmdlets used to manipulat...

 

This command displays the processes on the computer in groups with the same base priority class. The Wrap parameter assures that data is displayed on the next line, instead of being truncated.

 

PS D:\Windows\System32> get-process  | format-table -groupby basepriority -wrap

 

   BasePriority: 8

 

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

-------     ------       -----        -----     -----   ------        -- -----------

    120       4         12760       6696    40                 1168 audiodg

    155       5         48292        316     97      6.34     2036 avgamsvr

    188       7         48740        668    110     7.19     4000 avgcc

    154       7         47280       1684   101     6.25       216 avgemc

     50       4          46356      13516   83    21.16       304 avgrssvc

     59       2            1060        316    38      0.02       332 avgrssvc

     93       4            1860        668    48      0.08       236 avgupsvc

    232       7           9184       1440   75       6.27       496 BlueSoleilCS

     69       2            1004        468    30      0.05      2820 BsHelpCS

 

   BasePriority: 13

 

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

-------     ------       -----        -----     -----   ------        -- -----------

    552       5          1600       1364   132     1.91       520 csrss

    313       6        10776       8080   140    20.58       580 csrss

 

   BasePriority: 8

 

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

-------     ------       -----        -----     -----   ------        -- -----------

    131       5          2940       1288    58        0.31    4016 DPAgnt

    155       6          6760       1432    63        3.11      572 DpHost

 

This command displays information about the processes on the computer in group based on the start date of the process. The View parameter is used to select the StartTime view that is defined in the DotNetTypes.format.ps1xml for System.Diagnostics.Process objects, like those returned by Get-Process. This view converts the StartTime of the process to a short date and then groups the processes by start date.

 

PS D:\Windows\System32> get-process  | format-table -view starttime

 

ProcessName                  Id       HandleCount   WorkingSet

-----------                       --        -----------       ----------

audiodg                        1168           120          6856704

 

   StartTime.ToShortDateString(): 15-03-2008

 

ProcessName                  Id       HandleCount   WorkingSet

-----------                       --        -----------       ----------

avgamsvr                     2036           155           323584

avgcc                           4000           188           684032

avgemc                          216           155          1724416

avgrssvc                         304            50           13840384

 

 

This command displays all of the services on the computer in a table with two columns, "Name" and "DependentServices".

 

PS D:\Windows\System32> get-service | format-table -property name, dependentservices

 

Name                                                        DependentServices

----                                                            -----------------

AeLookupSvc                                                 {}

aspnet_state                                                 {}

AudioEndpointBuilder                                      {Audiosrv}

Audiosrv                                                       {}

BFE                                                              {SharedAccess, RemoteAccess, PolicyAgent, MpsSvc...}

CscService                                                    {}

DcomLaunch                                                 {wuauserv, WSearch, wscsvc, WPDBusEnum...}

DFSR                                                           {}

Dhcp                                                           {WinHttpAutoProxySvc}

ventlog                                                        {Schedule}

EventSystem                                                {SLUINotify, COMSysApp, SENS, DFSR...}

Fax                                                             {}

fdPHost                                                        {IPBusEnum}

LanmanServer                                              {Browser}

LanmanWorkstation                                      {SessionEnv, Netlogon, Browser}

 

 

This command shows how to use a calculated property in a table. The command displays a table with the process name and total running time of all Notepad processes on the local computer. The total running time is calculated by subtracting the start time of each process from the current time.

 

The TotalRunningTime property is specified by a hash table with two keys, "Label" and "Expression".

 

PS D:\Windows\System32> get-process notepad  | format-table processname, @{label="totalrunningtime"; Expression={ (get-date) - $_.starttime}}

 

ProcessName                                                  totalrunningtime

-----------                                                       ----------------

notepad                                                        00:35:01.2512535

 

 

Sponsors

Recent Articles

 

Get-PSSnapin

 

The Get-PSSnapIn cmdlet gets objects representing each Windows PowerShell snap-in available in the current console or registered on the system. The snap-ins are listed in the order in which they appear in the console file.

 

The -name parameter sets only the specified Windows PowerShell snap-ins. You can enter the names of one or more Windows PowerShell snap-ins, including wildcards.

 

The -registered parameter gets only the Windows PowerShell snap-ins that have been registered on the system. The snap-ins that are installed with Windows PowerShell do not appear in this list.

 

Examples:

 

This command get the Windows PowerShell snap-ins that are currently loaded in the console. This includes the snap-ins that are installed with Windows PowerShell and those that have been added to the console.

 

PS D:\Windows\System32> get-pssnapin

 

Name        : Microsoft.PowerShell.Core

PSVersion   : 1.0

Description : This Windows PowerShell snap-in contains Windows PowerShell management cmdlets used to manage components

              of Windows PowerShell.

 

Name        : Microsoft.PowerShell.Host

PSVersion   : 1.0

Description : This Windows PowerShell snap-in contains cmdlets used by the Windows PowerShell host.

 

Name        : Microsoft.PowerShell.Management

PSVersion   : 1.0

Description : This Windows PowerShell snap-in contains management cmdlets used to manage Windows components.

 

Name        : Microsoft.PowerShell.Security

PSVersion   : 1.0

Description : This Windows PowerShell snap-in contains cmdlets to manage Windows PowerShell security.

 

Name        : Microsoft.PowerShell.Utility

PSVersion   : 1.0

Description : This Windows PowerShell snap-in contains utility Cmdlets used to manipulate data.

 

This command gets the Windows PowerShell snap-ins in the current console that have names that begin with letter 'c' in Microsoft.PowerShell.

 

PS D:\Windows\System32> get-pssnapin -name microsoft.powershell.C*

 

Name        : Microsoft.PowerShell.Core

PSVersion   : 1.0

Description : This Windows PowerShell snap-in contains Windows PowerShell management cmdlets used to manage components

              of Windows PowerShell.

 

 

 

Tee-Object

 

This cmdlet is used to pipe an object input to a file or variable, then passes the input along the pipeline. To pipe the input to a file, specify the FilePath parameter. Piped objects are formatted by using the default formatter before they are stored in the specified file.  To store a reference to the input objects in a variable, specify the Variable parameter.

 

The -inputObject parameter specifies the object input to the cmdlet. Enter a variable that contains the objects or type a command or expression that gets the objects.

 

Examples:

 

This command gets a list of the processes running on the computer and sends the result to a file. Since there is no  second path listed, the result will be displayed in the console.

 

PS D:\Windows\System32> get-process | tee -filepath d:\users\bala\bb.txt

 

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

-------     ------       -----        -----   -----     ------        -- -----------

    121       4         12788       7148    40                 1120 audiodg

    158       5         48452        328    97     6.25       2020 avgamsvr

    189       7         48864        480   110     6.89       1960 avgcc

    ...

PS D:\Windows\System32> cd d:\users\bala

PS D:\users\bala> type bb.txt

 

 

This command get a list of the processes starting with letter 'w' running on the computer and sends the result to a variable named proc. It then pipes the resulting objects along to Select-Object, which selects the Id, ProcessName and Handles properties. Note that the $proc variable includes the default information returned by Get-Process.

 

PS D:\users\bala> get-process w* | tee -variable wproc | select-object id, processname,handles

 

Id    ProcessName                                                             Handles

--     -----------                                                                  -------

512  wininit                                                                         99

736  winlogon                                                                    126

1048 wmplayer                                                                  653

1052 wmpnetwk                                                                 328

3060 wmpnscfg                                                                  107

1564 wuauclt                                                                     144

860  wweb32                                                                       61

 

 

Select-Object

 

This cmdlet selects specified properties of an object or set of objects. It can also select unique objects from an array of objects or it can select a specified number of objects from the beginning or end of an array of objects.

 

You can use the First, Last and Unique parameters to select particular objects from an array of input objects. For  more powerful object filtering, use the Where-Object cmdlet. You can use Select-Object to add calculated properties to an object. To do so, you specify a hash table as a value of the Property parameter. The hash table must include two keys: Name and Expression. The value assigned to the Name key is used as the name of the property. The Expression key is assigned a script block that is evaluated to determine the value of the property.

 

Examples:

 

This command displays a list of processes. Only the name, ID and Working Set(WS) properties of the processes are displayed.

 

PS D:\users\bala> get-process | select-object processname, id, ws

 

ProcessName                   Id                       WS

-----------                        --                        --

audiodg                          1120                   7593984

avgamsvr                        2020                   233472

avgcc                              1960                   303104

 

 

This command displays information about the modules used by the processes running on a computer. It uses the ExpandProperty parameter to display the details contained within the modules property.

 

PS D:\users\bala> get-process notepad | select-object processname -expandproperty modules | format-list

 

ProcessName       : notepad

Size              : 160

Company           : Microsoft Corporation

FileVersion       : 6.0.6000.16386 (vista_rtm.061101-2205)

ProductVersion    : 6.0.6000.16386

Description       : Notepad

Product           : Microsoftr Windowsr Operating System

ModuleName        : NOTEPAD.EXE

FileName          : D:\Windows\system32\NOTEPAD.EXE

BaseAddress       : 7733248

ModuleMemorySize  : 163840

EntryPointAddress : 7746040

FileVersionInfo   : File:             D:\Windows\system32\NOTEPAD.EXE

                    InternalName:     Notepad

                    OriginalFilename: NOTEPAD.EXE.MUI

                    FileVersion:      6.0.6000.16386 (vista_rtm.061101-2205)

                    FileDescription:  Notepad

                    Product:          Microsoftr Windowsr Operating System

                    ProductVersion:   6.0.6000.16386

                    Debug:            False

                    Patched:          False

                    PreRelease:       False

                    PrivateBuild:     False

                    SpecialBuild:     False

                    Language:         English (United States)

Site              :

Container         :

...

 

The above example with no format-list option.

 

PS D:\users\bala> get-process smss | select-object processname -expandproperty modules

 

   Size(K) ModuleName                                         FileName

   -------   ----------                                              --------

        72   smss.exe                                             D:\Windows\system32\smss.exe

      1144  ntdll.dll                                                D:\Windows\system32\ntdll.dll

 

 

This command displays the 5 processes that are using the most memory. The Sort-Object cmdlet is used to sort the processes according to memory (Working Set) usage and the Select-Object cmdlet is used to select only the last 5 members of the resulting array of objects.

 

PS D:\users\bala> get-process | sort-object -property ws | select-object -last 5

 

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

-------  ------          -----        -----   -----      ------       -- -----------

    662      26         31524      12264   205    15.17   3896 explorer

   1340      41        20916      12968   109    19.45   1012 svchost

    648      25         57040      25408   214    43.66   3356 iexplore

    831      17         37200      30928   121    18.11   1000 svchost

    544      10         51324      34976   173    14.86   3124 powershell

 

This command displays unique strings from a list of strings supplied as input to the select-object cmdlet.

 

PS D:\users\bala> "C#", "c++", "C#", "VB", "j#", "VB" | select-object -unique

C#

c++

VB

j#

 

Sort-Object

 

This cmdlet sorts a set of objects by property values. You specify a property or set of properties to sort on by using the Property parameter. If multiple properties are specified, the objects are sorted and grouped from the first property, then the second property and so on.

 

The CaseSensitive parameter is specified for case-sensitive comparisons while sorting. To sort by some properties in ascendingorder and others in decending order, you must specify their property values by using a hashtable like the following:

 

    @{expression={$_.PropName},Descending=$true}.

 

Specifying this hashtable as a property value causes the cmdlet to sort on the value of the PropName property in decending order.

 

 

Examples:

 

This command gets the directories and files in the current directory starting with letter 'd'. The sort-object cmdlet, used without parameters, displays results in alphabetical order by name.

 

PS D:\Users\bala> get-item d* | sort-object

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

Mode                LastWriteTime     Length Name

----                -------------            ------  ----

d-r--        08-03-2008  17:24:08             Desktop

d-r--        11-03-2008  17:19:35             Documents

d-r--        02-03-2008  10:22:36             Downloads

 

This command displays the files in the current directory in ascending order by LastWriteTime.

 

PS D:\Users\bala> get-item d* | sort-object -property lastwritetime

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

Mode                LastWriteTime     Length Name

----                -------------            ------   ----

d-r--        02-03-2008  10:22:36             Downloads

d-r--        08-03-2008  17:24:08             Desktop

d-r--        11-03-2008  17:19:35             Documents

 

This command displays the 5 processes that are using the most memory. The Sort-Object cmdlet is used to sort the processes according to memory (Working Set) usage and the Select-Object cmdlet is used to select only the last 5 members of the resulting array of objects.

 

PS D:\users\bala> get-process | sort-object -property ws | select-object -last 5

 

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

-------  ------    -----      ----- -----   ------     -- -----------

    662      26    31524      12264   205    15.17   3896 explorer

   1340      41    20916      12968   109    19.45   1012 svchost

    648      25    57040      25408   214    43.66   3356 iexplore

    831      17    37200      30928   121    18.11   1000 svchost

    544      10    51324      34976   173    14.86   3124 powershell

This command lists all the files in the current directory with extension .txt in descending order.

 

PS D:\Users\bala> get-item *.txt | sort-object -descending

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala

 

Mode                LastWriteTime        Length    Name

----                       -------------        ------     ----

-a---        08-03-2008  11:18:01        272    myevents.txt

-a---        08-03-2008  11:16:48     647230  events.txt

-a---        12-03-2008  10:38:52      15260   bb.txt

 

Previous||Next