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,ConvertTo-Html,etc
Author: balamurali balaji

This tutorial is brought to you by BB Systems.

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


Previous||Next

ConvertTo-Html

 

This cmdlet creates an HTML page that represents objects. The cmdlet returns a complete HTML page.  The input objects are represented in a single HTML table within that page. The object property names appear as the HTML table column headings  and each of the rows in the table list the corresponding property values. Properties without values are represented  as blank cells in the table.

 

The -inputObject parameter specifies the objects to represent as an HTML table. It may be a variable that contains the objects or a command or expression that gets the objects.

To specify the properties of the input object to represent within the HTML table, use the -property parameter and to specify the text to include within the <body> element of the HTML output, use the -body parameter.

 

The -head and -title parameters can also be used to specify the text to be included in the respective tags.

 

Examples

 

This command uses the Get-Date cmdlet to create a DateTime object and pipe it to the ConvertTo-HTML cmdlet. The cmdlet creates an HTML page that includes an HTML table that represents the object. The HTML output is displayed at the console

 

PS D:\Users\bala> get-date | convertto-html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"  "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<title>HTML TABLE</title>

</head><body>

<table>

<colgroup>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

<col>

</colgroup>

<tr><th>DisplayHint</th>
<th>DateTime</th><th>Date</th><th>Day</th>
<th>DayOfWeek</th><th>DayOfYear</th><th>Hour</th><th>

Kind</th><th>Millisecond</th><th>Minute</th><th>Month</th>
<th>Second</th><th>Ticks</th><th>TimeOfDay</th><th>Year</th><

/tr>

<tr><td>DateTime</td><td>17 February 2008 10:26:11</td><td>17-02-2008 00:00:00</td><td>17</td><td>Sunday</td><td>48</td

><td>10</td><td>Local</td><td>373</td>
<td>26</td><td>2</td><td>11</td><td>633388407713730745</td><td>10:26:11.3730745</

td><td>2008</td></tr>

</table></body></html>

 

This command uses the Get-Process cmdlet to retrieve a set of objects that contain information about the processes, their name starting with letter "w" running on the computer. It pipes those objects to the ConvertTo-HTML cmdlet, which creates an HTML page that includes an HTML table that represents the objects. The Properties parameter is used to specify the properties of the objects that are represented in the table. The Title parameter specifies the title of the HTML page. The redirection    operator (>) is used to send the resulting HTML to a file named proc.htm. Finally, the Invoke-Item cmdlet is used to open the proc.htm file in the application associated with the .htm file name extension.

 

PS D:\Users\bala> get-process w* | convertto-html -property name, path, company -title "Process Information" > proc.htm

PS D:\Users\bala> type proc.htm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"  "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<title>Process Information</title>

</head><body>

<table>

<colgroup>

<col>

<col>

<col>

</colgroup>

<tr><th>name</th><th>path</th><th>company</th></tr>

<tr><td>wininit</td><td></td><td></td></tr>

<tr><td>winlogon</td><td></td><td></td></tr>

<tr><td>wmpnetwk</td><td></td><td></td></tr>

<tr><td>wmpnscfg</td><td>D:\Program Files\Windows Media Player\wmpnscfg.exe</td><td>Microsoft Corporation</td></tr>

<tr><td>wuauclt</td><td>D:\Windows\system32\wuauclt.exe</td><td>Microsoft Corporation</td></tr>

<tr><td>wweb32</td><td>D:\Program Files\WordWeb\wweb32.exe</td><td>Antony Lewis</td></tr>

</table></body></html>

 

To view the HTML file in the browser, issue the following command.

 

PS D:\Users\bala> invoke-item proc.htm

 

 

Convert-Path

 

This cmdlet converts a path from a Windows PowerShell path to a Windows PowerShell provider path.

 

The -path specifies the Windows PowerShell path to be converted.

The -literalPath specifies the path to be converted. The value of -LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single      quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

 

cvpa is the alias for this cmdlet.

 

Examples

 

This command expands the current working directory.

 

PS D:\Users\bala> convert-path ~

D:\Users\bala

 

This command converts the Windows PowerShell provider path to a standard registry path.

 

PS D:\Users\bala> convert-path hklm:\software\microsoft

 

HKEY_LOCAL_MACHINE\software\microsoft

 

Resolve-Path

 

Resolve-path cmdlet interprets the wildcard characters in a path and displays the items and containers at the location specified by the path, such as the files and folders or registry keys and subkeys. The names appear just as they are represented in the drive, including capitalization..

 

The  -path parameter specifies the Windows PowerShell path to resolve. The -literalPath parameter specifies the path to be resolved. The value of -LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

 

Examples

 

The ~ character signifies the home path. This example will return the full home path.

 

PS D:\Users\bala> resolve-path ~ | format-list

 

Drive        : D

Provider     : Microsoft.PowerShell.Core\FileSystem

ProviderPath : D:\Users\bala

Path         : D:\Users\bala

 

This example starts at the current location and returns the paths to all items in the Windows folder.

 

D:\Users\bala> resolve-path d:\windows\*

 

Path

----  

D:\windows\addins

D:\windows\AppPatch

D:\windows\assembly

D:\windows\ATK0100

D:\windows\Boot

D:\windows\Branding

D:\windows\CSC

D:\windows\Cursors

D:\windows\Debug

D:\windows\DigitalLocker

........

........

 

 

Get-WmiObject

 

This command gets instances of WMI classes or information about available classes. The ComputerName parameter can always be used  to target a remote computer. If the List parameter is specified, the cmdlet gets information about the WMI classes  available in a specified namespace. If the Query parameter is specified, the cmdlet runs a WMI query language (WQL) statement.

 

The -class and -property parameters specifies the name of a WMI class and its property or set of properties to retrieve.

 

The -namespace parameter specifies the WMI repository namespace where the referenced  WMI class is located. The   -credential parameter uses the specified credential to authenticate the user.

 

Examples

 

This command displays information about all of the processes running on a computer.

 

PS D:\Users\bala> get-wmiobject win32_process -property Name

 

__GENUS          : 2

__CLASS          : Win32_Process

__SUPERCLASS     :

__DYNASTY        :

__RELPATH        :

__PROPERTY_COUNT : 1

__DERIVATION     : {}

__SERVER         :

__NAMESPACE      :

__PATH           :

Name             : System Idle Process

 

__GENUS          : 2

__CLASS          : Win32_Process

__SUPERCLASS     :

__DYNASTY        :

__RELPATH        :

__PROPERTY_COUNT : 1

__DERIVATION     : {}

__SERVER         :

__NAMESPACE      :

__PATH           :

Name             : System

 

__GENUS          : 2

__CLASS          : Win32_Process

__SUPERCLASS     :

__DYNASTY        :

__RELPATH        :

__PROPERTY_COUNT : 1

__DERIVATION     : {}

__SERVER         :

__NAMESPACE      :

__PATH           :

Name             : smss.exe

 

This command displays information about the services on the local computer. It does so by specifying the IP address 127.0.0.1. This IP address can be changed to any other valid IP address on your network, enabling you to display information about the services on that remote computer. By default, the account you are running under must be a member of the local administrators group on the remote computer you specify for the command to succeed.

 

PS D:\Users\bala> get-wmiobject win32_service -computer 127.0.0.1

 

ExitCode  : 0

Name      : AeLookupSvc

ProcessId : 984

StartMode : Auto

State     : Running

Status    : OK

 

ExitCode  : 1077

Name      : ALG

ProcessId : 0

StartMode : Manual

State     : Stopped

Status    : OK

 

ExitCode  : 1077

Name      : Appinfo

ProcessId : 0

StartMode : Manual

State     : Stopped

Status    : OK

 

This command displays the WMI classes in the root/default namespace of the local computer.

 

PS D:\Users\bala> get-wmiobject -namespace "root/default" -list

 

__NotifyStatus                                              __ExtendedStatus

__SecurityRelatedClass                                      __Trustee

__NTLMUser9X                                                __ACE

__SecurityDescriptor                                        __PARAMETERS

__SystemClass                                               __ProviderRegistration

__EventProviderRegistration                                 __ObjectProviderRegistration

__ClassProviderRegistration                                 __InstanceProviderRegistration

__MethodProviderRegistration                                __PropertyProviderRegistration

__EventConsumerProviderRegistration                         __thisNAMESPACE

__NAMESPACE                                                 __IndicationRelated

__FilterToConsumerBinding                                   __EventConsumer

LogFileEventConsumer                                        ActiveScriptEventConsumer

NTEventLogEventConsumer                                     SMTPEventConsumer

CommandLineEventConsumer                                    __AggregateEvent

__TimerNextFiring                                           __EventFilter

__Event                                                     __NamespaceOperationEvent

__NamespaceModificationEvent                                __NamespaceDeletionEvent

__NamespaceCreationEvent                                    __ClassOperationEvent

__ClassDeletionEvent                                        __ClassModificationEvent

__ClassCreationEvent                                        __InstanceOperationEvent

__InstanceCreationEvent                                     __MethodInvocationEvent

__InstanceModificationEvent                                 __InstanceDeletionEvent

__TimerEvent                                                __ExtrinsicEvent

__SystemEvent                                               __EventDroppedEvent

__EventQueueOverflowEvent                                   __QOSFailureEvent

__ConsumerFailureEvent                                      RegistryEvent

RegistryKeyChangeEvent                                      RegistryTreeChangeEvent

RegistryValueChangeEvent                                    __EventGenerator

__TimerInstruction                                          __AbsoluteTimerInstruction

__IntervalTimerInstruction                                  __Provider

__Win32Provider                                             __CIMOMIdentification

__AdapStatus                                                __SystemSecurity

StdRegProv                                                  SystemRestoreConfig

SystemRestore

 

This command displays information about the IIS admin service.

 

PS D:\Users\bala> get-wmiobject -query "select * from win32_service where name='iisadmin'"

 

ExitCode  : 0

Name      : IISADMIN

ProcessId : 1904

StartMode : Auto

State     : Running

Status    : OK

 

You may run the above command to display IISadmin service information on a computer named balamurali-b. It specifies a user account name by using the Credential parameter, which causes a dialog to be displayed to gather the corresponding password.

 

PS D:\Users\bala> get-wmiobject -query "select name from win32_service where name='iisadmin'" -credential balamurali-b\bala -computer balamurali-b

 

 

 

Get-History

 

The Get-History cmdlet gets the session history, that is, the list of commands entered during the current session. Windows PowerShell automatically maintains a history of each session. You can save the session history in XML or CSV format. By default, history files are saved in the home directory, but you can save the file in any location.

 

The  -id parameter specifies the ID number of a command in the session history. Get-History gets only the specified command.

 

The -count parameter displays the specified number of most-recent history entries. The default is 32. If you use both Count and Id in a command, the display ends with the command specified by Id.

 

Examples

 

This command gets the 32 most recently submitted commands. The default display shows each command and its ID, which  indicates the order of execution.

 

PS D:\Users\bala> get-history

 

  Id CommandLine

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

   1 cls

   2 dir

   3 get-wmiobject

   4 get-wmiobject  win32_process

   5 get-wmiobject  win32_service

This command gets entries from the command history that include the word, "service". The first command gets the 32 most recent entries in the session history. The pipeline operator (|) passes the results to the Where-Object cmdlet , which selects only the commands that include "service".

 

PS D:\Users\bala> get-history | where-object {$_.commandLine -like "*service*"}

 

  Id  CommandLine

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

 12  get-wmiobject  win32_service

 

This command gets the 5 most recent history entries ending with entry 7. The pipeline operator (|) passes the result to the Export-Csv cmdlet, which formats the history as comma-separated text and saves it in the History.csv file.  The file includes the data that is displayed when you format the history as a list, including the status and start  and end times of the command.

 

PS D:\Users\bala> get-history -id 7 -count 5 | export-csv history.csv

 

This command gets the last (most recently entered) command in the command history. It uses the Count parameter to display just one command. By default, Get-History displays the most recent commands. This command can be abbreviated  to "h -c 1" and is equivalent to pressing the up-arrow key.

 

PS D:\Users\bala> get-history -count 1

 

  Id CommandLine

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

  20 get-history -id 2

 

This command displays all of the commands saved in the session history. By default, $MaximumHistoryCount is 64, so this command can be abbreviated as "h -c 64".

 

PS D:\Users\bala> get-history -count $maximumhistorycount

 

  Id CommandLine

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

  1 get-wmiobject  win32_process

  2 get-wmiobject  win32_service

  3 cls

  4 get-history

  5 get-history | where-object {$_.commandLine -like "*service*"}

  6 get-history -id 7 -count 5 | export-csv history.csv

  7 get-history -id -1

  8 get-history -id 1

  9 get-history -id 1

  10 get-history -id 2

  11 get-history -count 1

 

You may use format-list cmdlet along with the get-history command to display all of the properties of each history entry, including the ID, status, and start and end times of the command.

 

 

Add-History

 

The Add-History cmdlet adds entries to the end of the session history, that is, the list of commands entered during the current session. You can use Get-History to get the commands and pass them to Add-History, or export the commands to a CSV or XML file, then import the commands, and pass the imported file to Add-History. You can use this cmdlet to add specific commands to the history or to create a single history file that includes commands from more than one session.

 

The  -inputObject adds the specified HistoryInfo objects to the session history. You can use this parameter to submit a HistoryInfo object from Get-History, Import-Clixml, or Import-Csv to Add-History.

 

The -passthru parameter passes the object created by this cmdlet through the pipeline. By default, this cmdlet does not pass any objects through the pipeline.

 

Examples

 

These commands add the commands typed in one Windows PowerShell session to the history of a different Windows PowerShell session. The first command gets objects representing the commands in the history and exports them to the mycmdlets.csv file. The second command is typed at the command line of a different session. It uses the Import-Csv cmdlet  to import the objects in the mycmdlets.csv file. The pipeline operator passes the objects to the Add-History cmdlet,   which adds the objects representing the commands in the mycmdlets.csv file to the current session history.

 

PS D:\Users\bala> get-history | export-csv mycmdlets.csv

PS D:\Users\bala> type mycmdlets.csv

 

#TYPE Microsoft.PowerShell.Commands.HistoryInfo

Id,CommandLine,ExecutionStatus,StartExecutionTime,EndExecutionTime

1,"get-wmiobject  win32_process",Completed,"26-02-2008 19:00:02","26-02-2008 19:00:32"

2,"get-wmiobject  win32_service",Completed,"26-02-2008 19:00:38","26-02-2008 19:00:54"

3,cls,Completed,"26-02-2008 19:00:55","26-02-2008 19:00:55"

4,get-history,Completed,"26-02-2008 19:01:02","26-02-2008 19:01:02"

5,"get-history | where-object {$_.commandLine -like ""*service*""}",Completed,"26-02-2008 19:02:10","26-02-2008 19:02:10"

6,"get-history -id 7 -count 5 | export-csv history.csv",Completed,"26-02-2008 19:03:39","26-02-2008 19:03:40"

7,"get-history -id -1",Completed,"26-02-2008 19:07:13","26-02-2008 19:07:14"

 

PS D:\Users\bala> import-csv mycmdlets.csv | add-history

 

The following cmdlets are same as the above example and produces the same output. Without the Passthru parameter, Add-History does not generate any output to display.

 

PS D:\Users\bala> $a = import-csv mycmdlets.csv

PS D:\Users\bala> add-history -inputobject $a -passthru

or

PS D:\Users\bala> add-history -inputobject( import-csv mycmdlets.csv ) -passthru

 

This command adds the first five commands in the history to the end of the history list.

 

PS D:\Users\bala> get-history -id 5 -count 5 | add-history

 

 

 

Invoke-History

 

The Invoke-History cmdlet runs commands from the session history. You can pass objects representing the commands from Get-History to Invoke-History, or identify commands in the current history by using their ID number. To find the  identification number of a command, use Get-History.

 

The -iD parameter identifies a command in the history. You can type the ID number of the command or the first few characters of the command.

If you omit this parameter, Invoke-History runs the last (most recent) command.

 

Examples

 

Run the 'dir' command first and then execute the following cmd. This would run the last (most recent) command in the session history. You can abbreviate this command as "r" (think "repeat" or "rerun"), the alias for Invoke-History.

 

PS D:\Users\bala> invoke-history

dir

    

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

 

Mode                LastWriteTime    Length Name

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

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

d-r--        25-02-2008  17:42:46              Desktop

d-r--        24-02-2008  12:29:07              Documents

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

d-r--        25-02-2008  17:04:01              Favorites

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

 

This command runs the command in the session history with ID 80. Because the name of the -id parameter is optional, you can abbreviate this command as "Invoke-History 80", "ihy 80" or "r 80".

 

PS D:\Users\bala> invoke-history -id 80

get-history -id 2

 

The following cmdlet produces the same output as in the example above.

 

PS D:\Users\bala> get-history -id 80 | invoke-history

get-history -id 2

 

This command runs the most recent get-wmiobject command in the session history.

 

PS D:\Users\bala> invoke-history -id get-wmi

get-wmiobject  win32_service

 

 

Export-Console

 

The Export-Console cmdlet exports the configuration of the current console to a Windows PowerShell console file (.psc1). You can use this cmdlet to save a console configuration that you changed by changing its properties or by adding a Windows PowerShell snap-in to the console.

 

The parameter -path specifies a path and file name for the console file (*.psc1). This parameter is required unless you have exported a console file during the current session. It is also required when you use the NoClobber parameter to prevent the current console file from being overwritten.

 

Examples

 

This command exports the current console configuration to the MyConsole.psc1 file in the Consoles subdirectory of the directory stored in $pshome. By default, $pshome stores the path to the Windows PowerShell installation directory.

 

To see the value of this variable on your computer, type it.

 

PS D:\Windows\System32> $pshome

D:\Windows\System32\WindowsPowerShell\v1.0

 

Create a sub-directory named "Consoles" in the $pshome folder.

PS D:\Windows\System32> md $pshome\consoles

 

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

 

Mode                LastWriteTime     Length Name

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

d----        29-02-2008  17:49:27            consoles

 

Now, use the export-console command.

PS D:\Windows\System32> export-console -path $pshome\Consoles\MyConsole.psc1

 

See the contents of the myconsole.psc1 file

 

PS D:\Windows\System32> type $pshome\Consoles\MyConsole.psc1

<?xml version="1.0" encoding="utf-8"?>

<PSConsoleFile ConsoleSchemaVersion="1.0">

  <PSVersion>1.0</PSVersion>

  <PSSnapIns />

</PSConsoleFile>

 

This command exports the current console configuration to the Windows PowerShell console file in the current directory.

 

PS D:\Users\bala> export-console -path MyConsole.psc1

PS D:\Users\bala> type myconsole.psc1

<?xml version="1.0" encoding="utf-8"?>

<PSConsoleFile ConsoleSchemaVersion="1.0">

  <PSVersion>1.0</PSVersion>

  <PSSnapIns />

</PSConsoleFile>

 

The following command uses the $ConsoleFilename variable to find the name of the current console file.

 

PS D:\Windows\System32> $consolefilename

D:\Windows\System32\WindowsPowerShell\v1.0\Consoles\MyConsole.psc1

 

 

Export-Csv

 

The export-csv creates a comma-separated values (CSV) file that represents the input objects. EpCsv is the alias for this cmdlet.

 

Using the -path parameter, specify the path to the CSV to create. The -inputObject accepts objects that the cmdlet will represents as a CSV file. Enter a variable that contains the objects or type a command or expression that gets the objects.

 

Structure of the CSV file:

 

If the NoTypeInformation parameter is not specified, the first line of the CSV file contains the string '#TYPE ' followed by the fully-qualified name of the type being represented. For example: #TYPE System.Diagnostics.Process.   The next line of the CSV file represents column headers. It contains a comma-separated list of the names of all the properties of the first input object.  Additional lines of the file contain comma-separated lists of the values of each of the properties named in the column header line for each input object.

 

The first object establishes the column headers. The headers are not modified in response to subsequent input objects. If those objects do not include some of the properties in the column header line,two commas are written to indicate a missing property and ensure proper alignment of property values with the property names in the column headers.

 

Property values that contain commas, double quotes,  leading or trailing spaces, or line breaks, are put in double  quotes before being written to the CSV file. Any double quotes contained in a property are redoubled to indicate that they are literal.

 

You can use the Import-CSV cmdlet to use the information in the CSV file to recreate the input objects.

 

Examples

 

This command selects a few properties of the notepad  process and exports them to a CSV format file named data.csv.

 

PS D:\Windows\System32> get-process notepad | select-object basePriority, ID, SessionID, WorkingSet | export-csv -path data.csv

PS D:\Windows\System32> type data.csv

 

 

#TYPE System.Management.Automation.PSCustomObject

BasePriority,Id,SessionId,WorkingSet

8,2140,1,4677632

 

The following command first get all service information with names starting with letter 'v' and export the information to a file named servicedata.csv

 

PS D:\Windows\System32> get-service v* | export-csv -path servicedata.csv

PS D:\Windows\System32> type servicedata.csv

 

 

#TYPE System.ServiceProcess.ServiceController

Name,CanPauseAndContinue,CanShutdown,CanStop,DisplayName,DependentServices,
MachineName,ServiceName,ServicesDependedOn,S

erviceHandle,Status,ServiceType,Site,Container

vds,False,False,False,"Virtual Disk",System.ServiceProcess.ServiceController[],.,vds,System.ServiceProcess.ServiceContr

oller[],SafeServiceHandle,Stopped,Win32OwnProcess,,

VSS,False,False,False,"Volume Shadow Copy",System.ServiceProcess.ServiceController[],.,VSS,System.ServiceProcess.Servic

eController[],SafeServiceHandle,Stopped,Win32OwnProcess,,

 

 

Export-Clixml

 

This cmdlet creates an XML-based representation of an object or objects and stores it in a file. You can then use the Import-CLIXML cmdlet to recreate the saved object based on the contents of that file.

 

The -path parameter specify the path to the file where the XML representation of the object will be stored. The -inputObject parameter specify the object to be converted. The -depth parameter specify how many levels of contained objects should be included in the XML representation. eg. you must specify a depth of 2 to represent properties in xml file.

 

Examples

 

This command creates an XML file that stores a given string.

 

PS D:\Windows\System32> "Let this string be stored in xml file" | export-clixml simple.xml

PS D:\Windows\System32> type simple.xml

 

 

<Objs Version="1.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">

         <S>Let this string be stored in xml file</S>

</Objs>

 

This command get the information about notepad process and export it to xml file.

 

PS D:\Windows\System32> get-process notepad | export-clixml -path servicedata.xml

PS D:\Windows\System32> type servicedata.xml

 

 

<Objs Version="1.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">

<Obj RefId="RefId-0">

<TN RefId="RefId-0">

<T>System.Diagnostics.Process</T>

<T>System.ComponentModel.Component</T><T>System.MarshalByRefObject</T>

<T>System.Object</T>

</TN>

<Props>

<I32 N="BasePriority">8</I32><B N="HasExited">false</B><S N="Handle">1052</S>

<I32 N="HandleCount">56</I32>

<I32 N="Id">1412</I32><S N="MachineName">.</S><S N="MainWindowHandle">852636</S>

<S N="MainWindowTitle">data2 - Notepad</S>

<S N="MainModule">System.Diagnostics.ProcessModule (NOTEPAD.EXE)</S>

<S N="MaxWorkingSet">1413120</S><S N="MinWorkingSet">204800</S>

<Obj N="Modules" RefId="RefId-1"><TN RefId="RefId-1"><T>System.Diagnostics.ProcessModuleCollection</T>

<T>System.Collections.ReadOnlyCollectionBase</T>

<T>System.Object</T></TN><IE><S>System.Diagnostics.ProcessModule (NOTEPAD.EXE)</S><S>System.Diagnostics.ProcessModule (ntdll.dll)</S><S>System.Diagnostics.ProcessModule (kernel32.dll)</S><S>S

ystem.Diagnostics.ProcessModule (ADVAPI32.dll)</S><S>System.Diagnostics.ProcessModule (RPCRT4.dll)</S><S>System.Diagnos

tics.ProcessModule (GDI32.dll)</S><S>System.Diagnostics.ProcessModule (USER32.dll)</S><S>System.Diagnostics.ProcessModu

le (msvcrt.dll)</S><S>System.Diagnostics.ProcessModule (COMDLG32.dll)</S><S>System.Diagnostics.ProcessModule (SHLWAPI.d

ll)</S><S>System.Diagnostics.ProcessModule (COMCTL32.dll)</S><S>System.Diagnostics.ProcessModule (SHELL32.dll)</S><S>Sy

stem.Diagnostics.ProcessModule (WINSPOOL.DRV)</S><S>System.Diagnostics.ProcessModule (ole32.dll)</S><S>System.Diagnosti

cs.ProcessModule (OLEAUT32.dll)</S><S>System.Diagnostics.ProcessModule (IMM32.DLL)</S><S>System.Diagnostics.ProcessModu

le (MSCTF.dll)</S><S>System.Diagnostics.ProcessModule (LPK.DLL)</S><S>System.Diagnostics.ProcessModule (USP10.dll)</S><

S>System.Diagnostics.ProcessModule (uxtheme.dll)</S><S>System.Diagnostics.ProcessModule (CLBCatQ.DLL)</S></IE></Obj><I3

2 N="NonpagedSystemMemorySize">2592</I32><I64 N="NonpagedSystemMemorySize64">2592</I64><I32 N="PagedMemorySize">1429504

</I32><I64 N="PagedMemorySize64">1429504</I64><I32 N="PagedSystemMemorySize">42368</I32><I64 N="PagedSystemMemorySize64

">42368</I64><I32 N="PeakPagedMemorySize">1429504</I32><I64 N="PeakPagedMemorySize64">1429504</I64><I32 N="PeakWorkingS

et">4923392</I32><I64 N="PeakWorkingSet64">4923392</I64><I32 N="PeakVirtualMemorySize">41558016</I32><I64 N="PeakVirtua

lMemorySize64">41558016</I64><B N="PriorityBoostEnabled">true</B><S N="PriorityClass">Normal</S><I32 N="PrivateMemorySi

ze">1429504</I32><I64 N="PrivateMemorySize64">1429504</I64><TS N="PrivilegedProcessorTime">PT1.171875S</TS><S N="Proces

sName">notepad</S><S N="ProcessorAffinity">3</S><B N="Responding">true</B><I32 N="SessionId">1</I32><S N="StartInfo">Sy

stem.Diagnostics.ProcessStartInfo</S><DT N="StartTime">2008-02-29T18:26:15.913978+05:30</DT><Nil N="SynchronizingObject

" /><Obj N="Threads" RefId="RefId-2"><TN RefId="RefId-2">
<T>System.Diagnostics.ProcessThreadCollection</T><T>System.Col

lections.ReadOnlyCollectionBase</T><T>System.Object</T></TN><IE>
<S>System.Diagnostics.ProcessThread</S></IE></Obj><TS N

="TotalProcessorTime">PT2.015625S</TS><TS N="UserProcessorTime">PT0.84375S</TS><I32 N="VirtualMemorySize">41558016</I32

><I64 N="VirtualMemorySize64">41558016</I64><B N="EnableRaisingEvents">false</B><I32 N="WorkingSet">4923392</I32><I64 N

="WorkingSet64">4923392</I64><Nil N="Site" /><Nil N="Container" /></Props></Obj></Objs>

 

 

Export-Alias

 

This cmdlet exports information about currently-defined aliases within a specified namespace scope to a file. If the output file specified does not exist, the cmdlet will create it. It can export the alias information to comma-separated value(CSV) format or script (Script) format. EpAl is the alias for this cmdlet.

 

Structure of the File

 

The exported file includes the following header information preceded by the # comment symbol: Alias File, Exported by, Date/Time and Machine. The CSV format includes the name of the alias, the name of the corresponding cmdlet, the description of the alias if there is one, and the scope. The Script format includes the same information, but provides it as a set-alias command with the alias information provided as the value of the parameters to Set-Alias.

 

The -path specifies the path to the file in which to store alias information. The -name specifies the names of the aliases to export.

 

Examples

 

This command exports current alias information to a file named myalias.txt in the current directory.

 

 

PS D:\Users\bala> export-alias -path myalias.txt

PS D:\Users\bala> type myalias.txt

# Alias File

# Exported by : bala

# Date/Time : 03 March 2008 11:53:17

# Machine : BALAMURALI-B

"ac","Add-Content","","ReadOnly, AllScope"

"asnp","Add-PSSnapin","","ReadOnly, AllScope"

"clc","Clear-Content","","ReadOnly, AllScope"

"cli","Clear-Item","","ReadOnly, AllScope"

"clp","Clear-ItemProperty","","ReadOnly, AllScope"

"clv","Clear-Variable","","ReadOnly, AllScope"

"cpi","Copy-Item","","ReadOnly, AllScope"

"cpp","Copy-ItemProperty","","ReadOnly, AllScope"

"cvpa","Convert-Path","","ReadOnly, AllScope"

"diff","Compare-Object","","ReadOnly, AllScope"

"epal","Export-Alias","","ReadOnly, AllScope"

 

This command exports current alias information to a file named alias.txt. It includes a description in the header comment of the file and appends the exported information if the file named alias.txt exists and has content.

 

PS D:\Users\bala> export-alias -path alias.txt -append -description "Alias infomation file"

PS D:\Users\bala> notepad alias.txt

 

# Alias File

# Exported by : bala

# Date/Time : 03 March 2008 11:55:52

# Machine : BALAMURALI-B

#

# Alias infomation file

"ac","Add-Content","","ReadOnly, AllScope"

"asnp","Add-PSSnapin","","ReadOnly, AllScope"

"clc","Clear-Content","","ReadOnly, AllScope"

"cli","Clear-Item","","ReadOnly, AllScope"

"clp","Clear-ItemProperty","","ReadOnly, AllScope"

"clv","Clear-Variable","","ReadOnly, AllScope"

"cpi","Copy-Item","","ReadOnly, AllScope"

"cpp","Copy-ItemProperty","","ReadOnly, AllScope"

 

This command exports current alias information to a file named alias.txt. It overwrites any previous contents in that file if it exists. The alias information is exported as a series of commands that use the Set-Alias cmdlet. In the second line, the command opens the resulting exported file using Notepad.

 

PS D:\Users\bala> export-alias -path alias.txt -as script

PS D:\Users\bala> notepad alias.txt

 

# Alias File

# Exported by : bala

# Date/Time : 03 March 2008 12:00:35

# Machine : BALAMURALI-B

set-alias -Name:"ac" -Value:"Add-Content" -Description:"" -Option:"ReadOnly, AllScope"

set-alias -Name:"asnp" -Value:"Add-PSSnapin" -Description:"" -Option:"ReadOnly, AllScope"

set-alias -Name:"clc" -Value:"Clear-Content" -Description:"" -Option:"ReadOnly, AllScope"

set-alias -Name:"cli" -Value:"Clear-Item" -Description:"" -Option:"ReadOnly, AllScope"

set-alias -Name:"clp" -Value:"Clear-ItemProperty" -Description:"" -Option:"ReadOnly, AllScope"

set-alias -Name:"clv" -Value:"Clear-Variable" -Description:"" -Option:"ReadOnly, AllScope"

set-alias -Name:"cpi" -Value:"Copy-Item" -Description:"" -Option:"ReadOnly, AllScope"

set-alias -Name:"cpp" -Value:"Copy-ItemProperty" -Description:"" -Option:"ReadOnly, AllScope"

 

 

Import-Alias

 

This cmdlet is used to import an alias list from a file.

 

The -path parameter specifies the path to a file that includes exported alias information. Wildcards are allowed but they must resolve to a single name.

 

Example

 

To see how this cmdlet works, use the following cmdlets and instructions carefully.

 

1) Create a new alias "listallfiles" for the dir cmdlet.

 

PS D:\Users\bala> set-alias listallfiles dir

 

2) Issue the Export-alias cmdlet to export all the aliases to a text file.

 

PS D:\Users\bala> export-alias newaliases.txt

 

3) In the newaliases.txt, remove all the lines except the alias you just created.

 

# Alias File

# Exported by : bala

# Date/Time : 07 March 2008 19:01:18

# Machine : BALAMURALI-B

"listallfiles","dir","","None"

 

4) Now, Exit from the Windows PowerShell command console and re-open the console.

 

5) Import the alias info from a file newaliases.txt

PS D:\Users\bala> import-alias newaliases.txt

 

6) Run the alias and see the output for the dir cmdlet.

PS D:\Users\bala> listallfiles

 

 

 

Import-Csv

 

This cmdlet imports comma-separated value (CSV) files in the format produced by the Export-CSV cmdlet and returns objects that    correspond to the objects represented in that CSV file.

 

You must supply the path to the CSV file to import in the -path parameter

 

Example

 

This command  imports the history.csv file, once created using the export-csv command and it is piped output the $helper. On running the $helper, you would see the cmdlets re-executed.

 

PS D:\Users\bala> $helper = import-csv history.csv

PS D:\Users\bala> $helper

 

Id                 : 3

CommandLine        : help add-history

ExecutionStatus    : Completed

StartExecutionTime : 26-02-2008 18:53:23

EndExecutionTime   : 26-02-2008 18:53:24

 

Id                 : 4

CommandLine        : help get-history

ExecutionStatus    : Completed

StartExecutionTime : 26-02-2008 18:53:51

EndExecutionTime   : 26-02-2008 18:53:52

 

Id                 : 5

CommandLine        : help get-history -detailed

ExecutionStatus    : Completed

StartExecutionTime : 26-02-2008 18:54:00

EndExecutionTime   : 26-02-2008 18:54:02

 

Id                 : 6

CommandLine        : get-histroy

ExecutionStatus    : Completed

StartExecutionTime : 26-02-2008 18:59:29

EndExecutionTime   : 26-02-2008 18:59:29

 

Id                 : 7

CommandLine        : get-history

ExecutionStatus    : Completed

StartExecutionTime : 26-02-2008 18:59:33

EndExecutionTime   : 26-02-2008 18:59:33

 

 

Import-Clixml

 

This cmdlet  imports a CLIXML file and creates corresponding objects within Windows PowerShell.

 

The  -path parameter specify the location of the XML files to be converted into PSObjects.

 

Example

 

This command uses the Export-Clixml cmdlet to save a serialized copy of the notepad process information returned by Get-Process. It then uses Import-Clixml to retrieve the contents of the serialized file and recreate an object that is stored in the $notepad variable.

 

PS D:\Users\bala> get-process notepad | export-clixml mynote.xml

 

After exporting to the xml file, see the content.

 

PS D:\Users\bala> type mynote.xml

<Objs Version="1.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">

 <Obj RefId="RefId-0">

     <TN RefId="RefId-0">

 <T>System.Diagnostics.Process</T>

 <T>System.ComponentModel.Component</T>

 <T>System.MarshalByRefObject</T>

 <T>System.Object</T>

     </TN>

.........................

.........................

.........................

 

Now, import the xml file content to a variable.

PS D:\Users\bala> $notepad = import-clixml mynote.xml

 

When you check $notepad variable, you get the process information as expected.

PS D:\Users\bala> $notepad

 

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

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

    195       7     8044      13140    76     2.33   2632 notepad

 

 

 

Out-Null

 

This cmdlet deletes the output. Instead of sending it to the console, it sends output to NULL.

 

The -inputObject parameter specify the object that sent to null (deleted). Enter a variable that contains the objects or type a command or expression that gets the objects.

 

Example

 

This command gets the items in the local directory, but then discards them, instead of passing them through the pipeline or displaying them at the command line. This is useful for discarding output that you don't need.

 

PS D:\Users\bala>  get-childitem

 

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

 

Mode                LastWriteTime     Length Name

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

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

d-r--        06-03-2008  20:36:51            Desktop

d-r--        07-03-2008  07:09:22            Documents

............

............

 

PS D:\Users\bala>  get-childitem | out-null

PS D:\Users\bala>

 

As you see above, it returns no output.

 

Sponsors

Recent Articles

Out-Default

 

This cmdlet sends the output to the default formatter and the default output cmdlet. This cmdlet has no effect on the formatting  or output. It is a placeholder that lets you write your own Out-Default function or cmdlet.

 

It has only one parameter that is -inputobject that supplies the input to the command.

 

Example

 

This cmdlet list all the items in the current working directory in the default format.

 

PS D:\Users\bala> dir | out-default

 

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

 

Mode                LastWriteTime     Length Name

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

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

d-r--        14-03-2008  21:47:16            Desktop

d-r--        01-12-2007  11:49:42            Documents

..........

..........

 

 

 

Out-String

This cmdlet converts the objects that Windows PowerShell manages into an array of strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the stream parameter to direct Out-String to return one string at a time. This cmdlet lets you search and manipulate string output as you would in traditional shells when object manipulation is less convenient.

 

This command supports the  -inputObject,  -width and -stream parameters. Sends the strings for each object separately.

 

By default, the strings for each object are accumulated and sent  as a single string. With -stream parameter, strings for each object can be sent separately.

 

Examples

 

This command sends the content of the registry.txt file to the console as a single string.

 

PS D:\Users\bala> get-content registry.txt | out-string

 

Path                                                           Owner                                                Access

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

Microsoft.PowerShell.Core\Registry::... BUILTIN\Administrators                  BUILTIN\Users Allow  ReadKey...

 

These commands get the regional settings for the current user and convert the data to strings. The second command uses Out-String to convert the CultureInfo object to a series of strings; one for each property. The width parameter is set to 30 characters per line to prevent truncation.

 

PS D:\Users\bala> get-culture

 

LCID              Name             DisplayName

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

16393            en-IN               English (India)

 

PS D:\Users\bala> $cult = get-culture

PS D:\Users\bala> out-string -inputobject $cult -width 30

 

WARNING: column "DisplayName"

does not fit into the display

and was removed.

 

 

LCID                Name

----                     ----

16393              en-IN

 

 

Out-Host

This cmdlet sends output to the Windows PowerShell host for display. The host displays the output at the command line. Because Out-Host is the default, you do not need to specify it, unless you want to use its parameters to change the display.

 

The -paging parameter displays one page of output at a time, and waits for user input before displaying the remaining pages, lik e the traditional "more" command. By default, all of the output is displayed on a single page. The page size is  determined by the characteristics of the host.

 

The -inputObject specifies the objects that are written to the console. Enter a variable that contains the objects or type a command or expression that gets the objects.

 

Examples

 

This command displays the processes on the system one page at a time. It uses the Get-Process command to get the processes on the system. The pipeline operator (|) sends the results to Out-Host which displays them at the console. The Paging parameter displays one page of data at a time.

 

PS D:\Users\bala> get-process | out-host -paging

 

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

    106       3         12324         7380      39        1100              audiodg

    155       5         51408          328     100          588               avgamsvr

    153       7         50344         1692    104       1544               avgemc

.................

.................

.................

<SPACE> next page; <CR> next line; Q quit

    573       0              0                76       7             4                  System

<SPACE> next page; <CR> next line; Q quit

    125       4         2044           1944       43       3464              taskeng

     98        4         1252               52        26         476              wininit

    125       3         1880               88        31        704               winlogon

 

The same command format is used for the Help function that is built into Windows Powershell. That function gets data from Get-Help and then uses the Paging parameter of Out-Host to display the data one page at a time:

 

get-help $args[0] | out-host -paging.

 

These commands display the session history at the command line. The first command uses the Get-History cmdlet to get the session history, and then it stores the history in the $a variable. The second command uses Out-Host to display content of the $a variable and uses the InputObject parameter to specify the variable to Out-Host.

 

PS D:\Users\bala> $mycmdlets = get-history

PS D:\Users\bala> out-host -inputobject $mycmdlets

 

  Id CommandLine

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

   1 dir o*

   2 help out-default -detailed

   3 out-default

   4 help out-default -full

   5 cls

   6 out-default dir

   7 out-default | dir

   8 out-default | ls

   9 out-default | type alias.txt

  10 out-default

  11 dir | out-default

  12 dir

  13 dir | out-default

  14 dir o*

  15 help out-host -detailed

  16 cls

  17 get-process | out-host –paging

 

 

 

Out-Printer

 

The Out-Printer cmdlet sends output to the default printer or to an alternate printer, if one is specified.

The  -name parameter specifies the  alternate printer. The parameter name ("-Name") is optional.  The  -inputObject specifies the objects to be sent to the printer. Enter a variable that contains the objects or type a command or expression that gets the objects.

 

Examples

 

The following command prints the content of the file alias.txt.

 

PS D:\Users\bala> type alias.txt | out-printer

 

This command prints "Hello, World" to the "Canon ip1300" printer on the machine named balamurali-b. This command uses the Name parameter to specify the alternate printer. Because the parameter name is optional, you can omit it.

 

PS D:\Windows\System32\WindowsPowerShell\v1.0\documents\en-US> "hello world" | out-printer -name "\\balamurali-b\canon ip1300"

 

You may also use the inputobject parameter to supply the content to be printed. These commands print the full version of the help for Get-WmiObject stored in the $h variable.

 

PS D:\Windows\System32\WindowsPowerShell\v1.0\documents\en-US> $h = get-help -full get-wmiobject

PS D:\Windows\System32\WindowsPowerShell\v1.0\documents\en-US> out-printer -inputobject $h

 

 

Get-Culture

 

This cmdlet gets information about the regional settings on a computer. This includes information such as the current language

and keyboard layout.

 

Example

 

This command displays information about the regional settings on the computer.

 

PS D:\Users\bala> get-culture

 

LCID             Name             DisplayName

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

16393            en-IN            English (India)

 

 

Trace-Command

 

The Trace-Command cmdlet configures and starts a trace of the specified expression or command. It works like Set-TraceSource, except that it applies only to the specified command.

 

The -name parameter determines which Windows PowerShell components are traced. Enter the name of the trace source of each component.  In the  -expression parameter, you specify the expression that is being processed during the trace. Enclose the expression in curly braces ({}).

 

The  -option parameter decides the type of events that are traced. The valid values are: None, Constructor, Dispose, Finalizer, Method, Property, Delegates, Events, Exception, Lock, Error, Errors, Warning, Verbose, WriteLine, Data, Scope, ExecutionFlow, Assert, and All. "All" is the default value.

 

To  send the trace output to specified file, specify the  -filePath. To the debugger, use the  -debugger parameter so that you can view the output in any user-mode or kernel mode debugger or in  Visual Studio. To the PowerShell host, use the parameter -psHost.

 

Using the -listenerOption, you can add optional data to the prefix of each trace message in the output. The valid values are None, LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, and Callstack. "None" is the default.

 

The -command specify the cmdlet that is being traced and the -inputObject provides input to the expression that is being processed during the trace.

 

Examples

 

The following command starts a trace of metadata processing, parameter binding, and cmdlet creation and destruction of the "get-process notepad" expression. It uses the Name parameter to specify the trace sources, the Expression parameter to specify the command, and the PSHost parameter to send the output to the console. Because it does not specify any  tracing options or listener options, the command uses the defaults, "All" for the tracing options and "None" for the listener options.

 

PS D:\Users\bala> trace-command -name metadata,parameterbinding,cmdlet -expression {get-process notepad} -pshost

DEBUG: Cmdlet Information: 0 :  Constructor Enter Ctor Microsoft.PowerShell.Commands.GetProcessCommand: 64828693

DEBUG: Cmdlet Information: 0 :  Constructor Leave Ctor Microsoft.PowerShell.Commands.GetProcessCommand: 64828693

DEBUG: Metadata Information: 0 :  Constructor Enter Ctor System.Management.Automation.AliasAttribute: 56356440

DEBUG: Metadata Information: 0 :  Constructor Leave Ctor System.Management.Automation.AliasAttribute: 56356440

DEBUG: Metadata Information: 0 :  Constructor Enter Ctor System.Management.Automation.AliasAttribute: 56356440

DEBUG: Metadata Information: 0 :  Constructor Leave Ctor System.Management.Automation.AliasAttribute: 56356440

............

..............

.............

DEBUG: Cmdlet Information: 0 :  Method          Enter Cmdlet.DoEndProcessing():Get-Process

DEBUG: Cmdlet Information: 0 :  Method          Leave Cmdlet.DoEndProcessing()

 

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

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

    197             7               7952       11716         75         4.44      3692    notepad

 

The below command starts a trace of the command processor and pipeline processor while processing the "get-alias cd" command. It uses the Name parameter to specify the trace sources, the Command parameter to specify the command, the ArgumentList parameter to specify the parameters of the Get-Alias command, the Option parameter to specify tracing options, and the ListenerOption parameter to specify the fields in the trace message prefix. The FilePath parameters end the output to the Debug.txt file.

 

PS D:\Users\bala> trace-command -name commandprocessor,pipelineprocessor -command get-alias -argumentlist "ghy" -option executionflow -listenerOption "timestamp,callstack" -filepath debug.txt

 

CommandType           Name                                                  Definition

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

Alias                          ghy                                                     Get-History

 

In the below example, the first command stores the string "i*" in the $a variable. The second command uses the Trace-Command cmdlet with  the ParameterBinding trace source. The PSHost parameter sends the output to the console.

The expression being processed is "get-alias $input", where the $input variable is associated with the InputObject  parameter. The InputObject parameter passes the variable $a to the expression. In effect, the command being processed during the trace is "get-alias -inputobject $a" or "$a | get-alias".

 

PS D:\Users\bala> $a = "i*"

PS D:\Users\bala> trace-command parameterbinding {get-alias $input} -pshost -inputobject $a

 

DEBUG: ParameterBinding Information: 0 : BIND NAMED cmd line args [Get-Alias]

DEBUG: ParameterBinding Information: 0 : BIND POSITIONAL cmd line args [Get-Alias]

DEBUG: ParameterBinding Information: 0 :     BIND arg [System.Array+SZArrayEnumerator] to parameter [Name]

DEBUG: ParameterBinding Information: 0 :         Binding collection parameter Name: argument type [SZArrayEnumerator],

parameter type [System.String[]], collection type Array, element type [System.String], no coerceElementType

DEBUG: ParameterBinding Information: 0 :         Creating array with element type [System.String] and 1 elements

DEBUG: ParameterBinding Information: 0 :         Argument type SZArrayEnumerator is not IList, treating this as scalar

DEBUG: ParameterBinding Information: 0 :         BIND arg [System.Array+SZArrayEnumerator] to param [Name] SKIPPED

DEBUG: ParameterBinding Information: 0 :     BIND arg [System.Array+SZArrayEnumerator] to parameter [Name]

DEBUG: ParameterBinding Information: 0 :         COERCE arg type [System.Array+SZArrayEnumerator] to [System.String[]]

DEBUG: ParameterBinding Information: 0 :             ENCODING arg into collection

DEBUG: ParameterBinding Information: 0 :             Binding collection parameter Name: argument type

[SZArrayEnumerator], parameter type [System.String[]], collection type Array, element type [System.String],

coerceElementType

DEBUG: ParameterBinding Information: 0 :             Creating array with element type [System.String] and 1 elements

DEBUG: ParameterBinding Information: 0 :             Argument type SZArrayEnumerator is not IList, treating this as

scalar

DEBUG: ParameterBinding Information: 0 :             COERCE arg type [System.Array+SZArrayEnumerator] to

[System.String]

DEBUG: ParameterBinding Information: 0 :                 CONVERT arg type to param type using

LanguagePrimitives.ConvertTo

DEBUG: ParameterBinding Information: 0 :                 CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [i*]

DEBUG: ParameterBinding Information: 0 :             Adding scalar element of type String to array position 0

DEBUG: ParameterBinding Information: 0 :         BIND arg [System.String[]] to param [Name] SUCCESSFUL

DEBUG: ParameterBinding Information: 0 : MANDATORY PARAMETER CHECK on cmdlet [Get-Alias]

DEBUG: ParameterBinding Information: 0 : CALLING BeginProcessing

DEBUG: ParameterBinding Information: 0 : CALLING ProcessRecord

DEBUG: ParameterBinding Information: 0 : CALLING EndProcessing

 

CommandType     Name                                                Definition

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

Alias           iex                                                 Invoke-Expression

Alias           ihy                                                 Invoke-History

Alias           ii                                                  Invoke-Item

Alias           ipal                                                Import-Alias

Alias           ipcsv                                               Import-Csv

 

 

 

Get-UICulture

 

The Get-UICulture cmdlet gets information about the current user interface culture for Windows PowerShell and creates a CultureInfo object to store it. The UI culture includes settings for culture-specific information, such as language, sublanguage, time and date format, and cultural conventions. The UI culture differs from a culture in that the properties of a UI culture can change with each application.

 

Examples

 

This command gets the current UI culture information.

 

PS D:\Users\bala> get-uiculture

 

LCID             Name             DisplayName

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

1033             en-US             English (United States)

 

This command displays the values of all of the properties of the current UI culture in a list.

 

 

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

 

Parent                                   : en

LCID                                      : 1033

KeyboardLayoutId               : 1033

Name                                    : en-US

IetfLanguageTag                 : en-US

DisplayName                       : English (United States)

NativeName                         : English (United States)

EnglishName                       : English (United States)

TwoLetterISOLanguageName                   : en

ThreeLetterISOLanguageName                : eng

ThreeLetterWindowsLanguageName       : ENU

CompareInfo                        : CompareInfo - 1033

TextInfo                                 : TextInfo - 1033

IsNeutralCulture                   : False

CultureTypes                        : SpecificCultures, InstalledWin32Cultures, FrameworkCultures

NumberFormat                     : System.Globalization.NumberFormatInfo

DateTimeFormat                 : System.Globalization.DateTimeFormatInfo

Calendar                               : System.Globalization.GregorianCalendar

OptionalCalendars              : {System.Globalization.GregorianCalendar, System.Globalization.GregorianCalendar}

UseUserOverride                 : True

IsReadOnly                           : False

 

This command displays the current values for the Calendar property of the current UI culture. Calendar is just one  property of UI culture. To view all of the properties and methods of this object, type "Get-UICulture | Get-Member".

 

PS D:\Users\bala> (get-uiculture).Calendar

 

MinSupportedDateTime  : 01-01-0001 00:00:00

MaxSupportedDateTime : 31-12-9999 23:59:59

AlgorithmType                   : SolarCalendar

CalendarType                   : Localized

Eras                                   : {1}

TwoDigitYearMax             : 2029

IsReadOnly                        : False

 

These commands displays the short and long date pattern for the current UI culture. To see all of the subproperties and methods of the DateTimeFormat property of the UI culture, type "(get-uiculture).datetimeformat | gm".

 

PS D:\Users\bala> (get-uiculture).datetimeformat.shortdatepattern

M/d/yyyy

 

PS D:\Users\bala> (get-uiculture).datetimeformat.longdatepattern

dddd, MMMM dd, yyyy

 

Get-Unique

 

The Get-Unique cmdlet compares each item in a sorted list to the next item, eliminates duplicates, and returns only  one instance of each item. The list must be sorted for the cmdlet to work properly.

 

The parameter -inputObject accepts input for Get-Unique and treats the input as a collection, but with no enumeration of individual items.

The  -asString parameter treats the data as a string. Without this parameter, data is treated as an object, so when you submit a collection of objects of the same type to Get-Unique, such as a collection of files, it returns just one (the first). You may use this parameter to find the unique values of object properties, such as the file names.

 

The -onType parameter returns only one object of each type.

 

Examples

 

These commands find the number of unique words in a text file.  The first command gets the content of the File.txt file. It converts each line of text to lower case and then splits each word onto a separate line at the space (" "). Then, it sorts the resulting list alphabetically (the default), and uses the Get-Unique cmdlet to eliminate any duplicate words. The results are stored in the $a variable. The second command list those unique words and the third command uses the Count property of the collection of strings in $a to determine how many items are in $a

    .

PS D:\Users\bala> $a = $(foreach($line in get-content events.txt)

>> { $line.tolower().split(" ")}) | sort | get-unique

>> 

 

PS D:\Users\bala> $a

application

control

desktop

error

manager

rasclient

remoteaccess

securitycenter

service

tcpip

w32time

window

wlclntfy

 

PS D:\Users\bala> $a.count

13

 

The following command finds the unique members of the set of integers sorted.

 

PS D:\Users\bala> 12,2,4,6,2,7,4,1,12,11,6,2,5 | sort-object | get-unique

1

2

4

5

6

7

11

12

 

The following command retrieve the contents of the local directory (files and folders) and by  appliying the GetType method to each file or directory using "$_.GetType()" statement. The OnType parameter directs Get-Unique to return only one object of each type.

 

PS D:\Users\bala> get-childitem | sort-object {$_.gettype()} | get-unique -ontype

 

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

 

Mode                   LastWriteTime     Length                    Name

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

d-r--        25-02-2008  05:07:00                        Saved Games

-a---        07-03-2008  19:01:18       4474         newaliases.txt

 

This command gets the names of processes running on the computer with duplicates eliminated. The AsString parameter tells Get-Unique to treat the ProcessName values as strings. Without this parameter, Get-Unique treats the ProcessName values as objects, and returns only one instance of the object, that is, the first process name in the list.

 

PS D:\Users\bala> get-process | sort-object | select processname | get-unique -asstring

 

ProcessName

-----------

audiodg

avgamsvr

avgcc

avgemc

avgrssvc

 

 

Get-Acl

 

The Get-Acl cmdlet gets objects that represent the security descriptor of a file or resource. The security descriptor contains the access control lists (ACLs) of the resource. The ACL specifies the permissions that users and user groups that have to access the resource.

 

The -path parameter specifies the path to a resource. You may also specify filter in the provider format using the -filter parameter. Using filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

 

Examples

The following commands gets the security descriptor of the Windows directory.

 

PS D:\Users\bala>  get-acl d:\windows

 

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

 

Path                                        Owner                                                       Access

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

windows                                   NT SERVICE\TrustedInstaller                        CREATOR OWNER Allow  268435456...

 

The above command with format-list.

 

PS D:\Users\bala>  get-acl d:\windows | format-list

 

Path   : Microsoft.PowerShell.Core\FileSystem::D:\windows

Owner  : NT SERVICE\TrustedInstaller

Group  : NT SERVICE\TrustedInstaller

Access : CREATOR OWNER Allow  268435456

         NT AUTHORITY\SYSTEM Allow  268435456

         NT AUTHORITY\SYSTEM Allow  Modify, Synchronize

         BUILTIN\Administrators Allow  268435456

         BUILTIN\Administrators Allow  Modify, Synchronize

         BUILTIN\Users Allow  -1610612736

         BUILTIN\Users Allow  ReadAndExecute, Synchronize

         NT SERVICE\TrustedInstaller Allow  268435456

         NT SERVICE\TrustedInstaller Allow  FullControl

Audit  :

Sddl   : O:S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464G:S-1-5-80-956008885-3418522649-1831038044-185

         3292631-2271478464D:PAI(A;OICIIO;GA;;;CO)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;BA)(A;;0x1301bf;;;

         BA)(A;OICIIO;GXGR;;;BU)(A;;0x1200a9;;;BU)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271

         478464)(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)

 

These commands uses Get-Acl to get the security descriptor of the registry subkey.

 

PS D:\Users\bala> get-acl -path hklm:\software\mycompany

 

Path                                                            Owner                                            Access

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

Microsoft.PowerShell.Core\Registry::...             BUILTIN\Administrators                    BUILTIN\Users Allow  ReadKey...

 

The above command with format-list.

 

PS D:\Users\bala> get-acl -path hklm:\software\mycompany | format-list

 

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

Owner  : BUILTIN\Administrators

Group  : balamurali-b\None

Access : BUILTIN\Users Allow  ReadKey

         BUILTIN\Users Allow  -2147483648

         BUILTIN\Administrators Allow  FullControl

         BUILTIN\Administrators Allow  268435456

         NT AUTHORITY\SYSTEM Allow  FullControl

         NT AUTHORITY\SYSTEM Allow  268435456

         CREATOR OWNER Allow  268435456

Audit  :

Sddl   : O:BAG:S-1-5-21-3999078112-1667691215-1305967113-513D:AI(A;ID;KR;;;BU)(A;CIIOID;GR;;;BU)(A;ID;KA;;;BA)(A;CIIOID

         ;GA;;;BA)(A;ID;KA;;;SY)(A;CIIOID;GA;;;SY)(A;CIIOID;GA;;;CO)

 

 

Get-Command

 

This command gets basic information about cmdlets and other elements of Windows PowerShell commands, such as files, functions, and Windows PowerShell providers.

 

The -name parameter gets information only about the cmdlets or command elements with the specified name. With the -verb parameter, you receive cmdlets with names including the specified verb. -noun parameter gets cmdlets with names that include the specified noun.

 

The -commandType  parameter dets only the specified types of command objects. Valid values for <CommandTypes> are: Alias, ExternalScript, All, Filter, Application, Function, Cmdlet (default type)  and Script

 

"Application" represents all non-PowerShell files on the system that you can run within PowerShell, including .txt, .exe. and .dll files in the Windows PowerShell path.

 

"Filter" and "Function" represent all Windows PowerShell functions.

 

Examples

 

This command retrieves information about all of the Windows PowerShell cmdlets with the command type ("Cmdlet"), the name of the cmdlet, and the syntax.

 

PS D:\Users\bala> get-command

 

CommandType     Name                            Definition

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

Cmdlet          Add-Content                        Add-Content [-Path] <String[]> [-Value] <Object[...

Cmdlet          Add-History                          Add-History [[-InputObject] <PSObject[]>] [-Pass...

Cmdlet          Add-Member                        Add-Member [-MemberType] <PSMemberTypes> [-Name]...

 

Cmdlet          Add-PSSnapin                      Add-PSSnapin [-Name] <String[]> [-PassThru] [-Ve...

...........

...........

 

The following command retrieves information about all of the cmdlets with the verb "set," and displays some of that information in a list. Only one command is listed as output for sample.

 

PS D:\Users\bala> get-command -verb set | format-list

 

Name                      : Set-Acl

CommandType         : Cmdlet

Definition                 : Set-Acl [-Path] <String[]> [-AclObject] <ObjectSecurity> [-Passthru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-ErrorVariabl e <String>] [-OutVariable <String>] [-OutBuffer <Int32>] [-WhatIf] [-Confirm]

 

Path                        :

AssemblyInfo           :

DLL                         : D:\Windows\assembly\GAC_MSIL\Microsoft.PowerShell.Security\ 1.0.0.0__31bf3856ad364e35\Microsoft.PowerShell.Security.dll

HelpFile                   : Microsoft.PowerShell.Security.dll-Help.xml

ParameterSets         : {__AllParameterSets}

ImplementingType   : Microsoft.PowerShell.Commands.SetAclCommand

Verb                       : Set

Noun                      : Acl

 

This command retrieves information about the cmdlets in the Microsoft.PowerShell.Security PSSnapin.

 

PS D:\Users\bala> get-command -pssnapin Microsoft.PowerShell.Security

 

CommandType     Name                                         Definition

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

Cmdlet          ConvertFrom-SecureString           ConvertFrom-SecureString [-SecureString] ....

Cmdlet          ConvertTo-SecureString              ConvertTo-SecureString [-String] <String> [[-Sec...

Cmdlet          Get-Acl                                     Get-Acl [[-Path] <String[]>] [-Audit] [-Filter <...

Cmdlet          Get-AuthenticodeSignature          Get-AuthenticodeSignature [-FilePath] <String[]>...

Cmdlet          Get-Credential                           Get-Credential [-Credential] <PSCredential> [-Ve...

Cmdlet          Get-ExecutionPolicy                    Get-ExecutionPolicy [-Verbose] [-Debug] [-ErrorA...

Cmdlet          Get-PfxCertificate                       Get-PfxCertificate [-FilePath] <String[]> [-Verb...

Cmdlet          Set-Acl                                      Set-Acl [-Path] <String[]> [-AclObject] <ObjectS...

Cmdlet          Set-AuthenticodeSignature          Set-AuthenticodeSignature [-FilePath] <String[]>...

Cmdlet          Set-ExecutionPolicy                    Set-ExecutionPolicy [-ExecutionPolicy] <Executio...

 

This command retrieves only parameters that are added to the Get-Childitem cmdlet dynamically when it is used with  the Windows PowerShell Certificate provider.

 

PS D:\Users\bala> (get-command get-childitem -ArgumentList cert:).parametersets[0].parameters | where-object { $_.IsDyna

mic }

 

 

Name                                   : CodeSigningCert

ParameterType                      : System.Management.Automation.SwitchParameter

IsMandatory                          : False

IsDynamic                             : True

Position                                 : -2147483648

ValueFromPipeline                  : False

ValueFromPipelineByPropertyName   : False

ValueFromRemainingArguments       : False

HelpMessage                          :

Aliases                                   : {}

Attributes                                : {__AllParameterSets}

Previous||Next