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

Get-EventLog

 

This cmdlet gets information about local event logs or the entries stored in those event logs.

The parameter -logName indicates the name of the log file from which to get events. The -list returns a list of all event logs, rather than the entries from a specific log. -asString sends the output as strings instead of objects.

 

The -newest parameter gets the newest 'n' event log entries, where   'n' represents a numerical value for the newest  entries in the eventlog.

Examples

 

The command below displays information about the event logs on the computer.

 

PS D:\Users\bala> get-eventlog -list

 

  Max(K)      Retain  OverflowAction              Entries    Name

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

  20,480      0          OverwriteAsNeeded      46,318    Application

  15,168      0          OverwriteAsNeeded           0         DFS Replication

  20,480      0          OverwriteAsNeeded           0         Hardware Events

     512        7          OverwriteOlder                 0         Internet Explorer

     512        7          OverwriteOlder                 0         Key Management Service

  16,384      0          OverwriteAsNeeded           4         Microsoft Office Diagnostics

  16,384      0          OverwriteAsNeeded        1,078     Microsoft Office Sessions

  20,480      0          OverwriteAsNeeded       57,116    System

  15,360      0          OverwriteAsNeeded         1,076     Windows PowerShell

 

This command displays the 3 most recent entries in the Application event log.

 

PS D:\Users\bala> get-eventlog -newest 3 -logname application

 

Index  Time                Type  Source                        EventID  Message

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

57600 Dec 19 16:47  Info   MSSQL$SQLEXPRESS        17403    Server resumed execution after being idle 1792 seconds. Reaso...

57599 Dec 19 16:39  Info   MSSQL$SQLEXPRESS        17896    The time stamp counter of CPU on scheduler id 1 is not synchr...

57598 Dec 19 16:19  Info   SecurityCenter                         1             The Windows Security Center Service has started.

 

This command gets the 10 most recent entries from the System event log and stores them in the $events variable. The results are then pipelined to the group-object cmdlet to group them by event id.

 

PS D:\Users\bala> $events = get-eventlog -logname system -newest 10

PS D:\Users\bala>   $events | group-object eventid

 

Count    Name                       Group

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

    7      7036                      {balamurali-b, balamurali-b, balamurali-b, balamurali-b...}

    1     14204                     {balamurali-b}

    1     134                         {balamurali-b}

    1     10029                     {balamurali-b}

 

Get-Location

 

This cmdlet gets information about the current working location.

 

The  -psProvider parameter outputs a PathInfo object representing the current working location for the specified providers.

 

The  -psDrive parameter outputs a PathInfo object representing the current working location for the specified drives.

 

The -stack and - stackName parameters outputs a StackInfo object representing the current and specified stack respectively.

 

Examples:\

 

This command displays the current working location.

 

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

 

Drive              : D

Provider          : Microsoft.PowerShell.Core\FileSystem

ProviderPath    : D:\Users\bala

Path               : D:\Users\bala

 

 

Get-PSProvider

 

This cmdlet gets information about the specified Windows PowerShell provider.

 

The -psProvider parameter specifies the name or names of the Windows PowerShell providers about which to retrieve information.

 

Examples

 

This command displays a list of all available Windows PowerShell providers.

 

PS D:\Users\bala> get-psprovider

 

Name                   Capabilities                                        Drives

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

Alias                    ShouldProcess                                     {Alias}

Environment         ShouldProcess                                     {Env}

FileSystem           Filter, ShouldProcess                            {C, D, E, F...}

Function              ShouldProcess                                     {Function}

Registry              ShouldProcess                                     {HKLM, HKCU}

Variable              ShouldProcess                                     {Variable}

Certificate           ShouldProcess                                     {cert}

 

This command displays a list of all Windows PowerShell providers with names that begin with the letters 'fi' or 're'.

 

PS D:\Users\bala> get-psprovider fi*, re* | format-list

 

Name                : FileSystem

Drives                : {C, D, E, F...}

Path                  :

Home                : D:\Users\bala

Description         :

Capabilities        : Filter, ShouldProcess

ImplementingType : Microsoft.PowerShell.Commands.FileSystemProvider

AssemblyInfo        :

 

Name                 : Registry

Drives                 : {HKLM, HKCU}

Path                   :

Home                 :

Description          :

Capabilities         : ShouldProcess

ImplementingType : Microsoft.PowerShell.Commands.RegistryProvider

AssemblyInfo         :

 

Get-Service

 

The Get-Service cmdlet gets objects representing the services on the local computer, including running and stopped services. You can direct Get-Service to get only particular services by specifying the service name or display name of the services using the -name and -displayname parameters, or you can use the InputObject parameter to supply a service object representing each of the services that you want to retrieve.

 

Examples

 

This command retrieves all of the services on the system.  The default display shows the status, service name, and display name of each service.

 

PS D:\Users\bala> get-service

 

Status      Name                    DisplayName

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

Running   AeLookupSvc           Application Experience

Stopped   ALG                        Application Layer Gateway Service

Stopped   Appinfo                   Application Information

Stopped   AppMgmt                Application Management

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

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

 

This command retrieves services with service display names that begin with "WMI".

 

PS D:\Users\bala> get-service -displayname wmi*

 

Status      Name                  DisplayName

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

Stopped   wmiApSrv             WMI Performance Adapter

 

These commands display only the services with service names that begin with "RPC" from a list of service names stored in the $services variable. 

 

PS D:\Users\bala> $myservice = get-service

PS D:\Users\bala> get-service -inputobject $myservice -include RPC*

 

Status      Name                   DisplayName

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

Stopped   RpcLocator            Remote Procedure Call (RPC) Locator

Running   RpcSs                   Remote Procedure Call (RPC)

 

This command displays only the services that are currently running.

 

PS D:\Users\bala> get-service | where-object {$_.Status -eq "Stopped"}

 

Status       Name                 DisplayName

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

Stopped  ALG                      Application Layer Gateway Service

Stopped  Appinfo                 Application Information

Stopped  AppMgmt              Application Management

Stopped  aspnet_state         ASP.NET State Service

 

 

Get-PfxCertificate

 

This cmdlet gets an object representing each specified .pfx certificate file. A .pfx file includes both the certificate and a private key.

 

The  -filePath parameter specifies the full path to the .pfx file of the secured file.

 

Examples

 

The following command gets information about the www.fabrikam.com.pfx certificate available with the VS2008 training kit.

 

PS D:\Users\bala> $fp = "D:\VS2008TrainingKit\Labs\CardSpace\Setup\scripts\certs\www.fabrikam.com.pfx"

PS D:\Users\bala> get-pfxcertificate -filepath $fp | format-list

 

Subject             : CN=www.fabrikam.com, O=Fabrikam, L=Redmond, S=Washington, C=US

Issuer              : CN=Adatum, DC=ntdev, DC=corp, DC=microsoft, DC=com

Thumbprint       : D47DE657FA4902555902CB7F0EDD2BA9B05DEBB8

FriendlyName    : Fabrikam

NotBefore         : 20-05-2006 05:12:33

NotAfter           : 10-03-2011 23:57:56

Extensions       : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid...}

 

Get-ExecutionPolicy

 

This cmdlet gets the execution policy that is effective in the shell. The execution policy is determined by the user preference that you set by using Set-ExecutionPolicy and the Group Policy settings for the Windows PowerShell execution policy. The default is "Restricted."

 

 

This cmdlet has no special parameters except that it supports the common parameters like -Verbose, -Debug,  -ErrorAction, -ErrorVariable, and -OutVariable.

 

Examples

 

This command gets the current execution policy for the shell.

 

PS D:\Users\bala> get-executionpolicy

Restricted

 

Get-AuthenticodeSignature

 

This cmdlet gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but it the fields are blank.

 

The  -filePath parameter specifies the path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional.

 

Examples

 

This command gets information about the Authenticode signature in the myconsole.psc1 file. It uses the Filepath parameter to specify the file.

 

PS D:\> get-authenticodesignature d:\users\bala\myconsole.psc1

 

    Directory: D:\users\bala

 

SignerCertificate                         Status                                 Path

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

                                                UnknownError                       myconsole.psc1

 

Get-Host

 

This cmdlet gets a reference to the current console host object. Displays Windows Powershell version and regional information by default. This cmdlet can be used to access objects that enable you to manipulate the console user interface.

 

Examples

 

This command displays information about the current shell.

 

PS D:\> get-host

 

Name                : ConsoleHost

Version             : 1.0.0.0

InstanceId        : 4610a822-efa5-45bc-9530-d42eca72f88b

UI                      : System.Management.Automation.Internal.Host.InternalHostUserInterface

CurrentCulture : en-IN

CurrentUICulture : en-US

PrivateData          : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy

 

This command assigns the host object to a variable and looks at various properties and methods of the host object.

 

PS D:\> $ho = get-host

PS D:\> $ho | get-member

 

   TypeName: System.Management.Automation.Internal.Host.InternalHost

 

Name                            MemberType   Definition

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

EnterNestedPrompt          Method     System.Void EnterNestedPrompt()

Equals                            Method     System.Boolean Equals(Object obj)

ExitNestedPrompt             Method     System.Void ExitNestedPrompt()

GetHashCode                   Method     System.Int32 GetHashCode()

GetType                          Method     System.Type GetType()

get_CurrentCulture           Method     System.Globalization.CultureInfo get_CurrentCulture()

get_CurrentUICulture        Method     System.Globalization.CultureInfo get_CurrentUICulture()

get_InstanceId                Method     System.Guid get_InstanceId()

get_Name                       Method     System.String get_Name()

get_PrivateData               Method     System.Management.Automation.PSObject get_PrivateData()

get_UI                            Method     System.Management.Automation.Host.PSHostUserInterface get_UI()

get_Version                    Method     System.Version get_Version()

NotifyBeginApplication     Method     System.Void NotifyBeginApplication()

NotifyEndApplication        Method     System.Void NotifyEndApplication()

SetShouldExit                 Method     System.Void SetShouldExit(Int32 exitCode)

ToString                         Method     System.String ToString()

CurrentCulture                Property   System.Globalization.CultureInfo CurrentCulture {get;}

CurrentUICulture             Property   System.Globalization.CultureInfo CurrentUICulture {get;}

InstanceId                      Property   System.Guid InstanceId {get;}

Name                             Property   System.String Name {get;}

PrivateData                     Property   System.Management.Automation.PSObject PrivateData {get;}

UI                                  Property   System.Management.Automation.Host.PSHostUserInterface UI {get;}

Version                            Property   System.Version Version {get;}

 

This command resizes the Windows PowerShell window to 50 pixels by 50 pixels.

 

PS D:\> $h = get-host

PS D:\> $win = $h.ui.rawui.windowsize

PS D:\> $win.height = 50

PS D:\> $win.width  = 50

PS D:\> $h.ui.rawui.set_windowsize($win)

 

Get-Variable

 

This cmdlet gets the Windows PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter and you can filter the variables returned by name.

 

The parameters -name specifies the name of the variable. The -valueOnly parameter gets only the value of the variable. The -scope limits the variables retrieved to the specified scope. The value can be a named scope: "global", "local", or "script", "private" or it can be a number relative to the current scope (0 through the number of scopes where 0 is the current scope and increasing the number by 1 moves to the parent scope of the current scope).

 

Examples

 

This command displays variables with names that begin with the letter 'm'. The value of the variables is also displayed.

 

PS D:\> get-variable m*

 

Name                                           Value

----                                                 -----

MaximumHistoryCount                 64

MaximumAliasCount                4096

MaximumFunctionCount          4096

MyInvocation                             System.Management.Automation.InvocationInfo

MaximumErrorCount                  256

MaximumDriveCount                4096

MaximumVariableCount           4096

 

This command displays only the values of the variables with names that begin with the letter 'm'.

 

PS D:\> get-variable m* -valueonly

64

4096

4096

 

MyCommand          : get-variable m* -valueonly

ScriptLineNumber  : 0

OffsetInLine           : 0

ScriptName            :

Line                         :

PositionMessage   :

InvocationName     :

PipelineLength       : 2

PipelinePosition     : 1

 

256

4096

4096

 

This command gets information about the variables that begin with either the letter 'C' or the letter 'P'. The results are piped to the Sort-Object cmdlet, sorted by name and displayed.

 

PS D:\> get-variable -include c*, p* | sort-object name

 

Name                                    Value

----                                       -----

ConfirmPreference                  High

ConsoleFileName

PID                                       2412

PROFILE                             D:\Users\bala\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

ProgressPreference                 Continue

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

PWD                                     D:\

 

Get-TraceSource

 

This cmdlet gets the trace sources for Windows PowerShell components that are currently in use. You  can use the data to determine which Windows PowerShell components you can trace. When tracing, the component generates detailed messages about each step in its internal processing. Developers use the trace data to monitor data flow, program execution, and errors. The tracing cmdlets were designed for Windows PowerShell developers, but are available to all users.

 

The name parameter gets only the specified trace sources. Wildcards are permitted. The parameter name ("-Name") is optional.

 

Examples

 

This command gets all of the trace sources that have names that include "provider".

 

PS D:\> get-tracesource *provider*

 

Options  Name                       Listeners           Description

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

None      CmdletProviderAt      {Default}            The attribute that declares that a class is an implementation of ..

None      ProviderConfigur       {Default}            ProviderConfigurationEntry

None      ProviderCommandA {Default}            The APIs that are exposed to the Cmdlet base class for manipulati..

None     CmdletProviderIn       {Default}            The APIs that are exposed to the Cmdlet base class for manipulati..

None     ProviderIntrinsi           {Default}            The APIs that are exposed to the Cmdlet base class for manipulati..

None     CoreCommandProvi  {Default}            The namespace navigation tracer

None     AliasProvider              {Default}            The CmdletProvider for shell aliases

None     CmdletProviderCl      {Default}            The namespace provider base classes tracer

None     CmdletProviderCo     {Default}            The context under which a core command is being run.

None     EventLogLogProvi     {Default}            EventLogLogProvider

None     EnvironmentProvi      {Default}             The core command provider for environment variables

None     FileSystemProvid      {Default}             The namespace navigation provider for the file system

None     VariableProvider       {Default}              The core command provider for shell variables

None     RegistryProvider       {Default}              The namespace navigation provider for the Windows Registry

None     CertificateProvi          {Default}             The core command provider for certificates

None     HelpProvider              {Default}             HelpProvider

None     AliasHelpProvide       {Default}             AliasHelpProvider

None     HelpProviderWith       {Default}             HelpProviderWithCache

None     CommandHelpProvi   {Default}            CommandHelpProvider

None     ProviderHelpProv       {Default}            ProviderHelpProvider

None     HelpFileHelpProv       {Default}            HelpFileHelpProvider

None     HelpProviderWith       {Default}            HelpProviderWithFullCache

None     FaqHelpProvider        {Default}            FaqHelpProvider

None     GlossaryHelpProv      {Default}            GlossaryHelpProvider

None     GeneralHelpProvi       {Default}            GeneralHelpProvider

None     DefaultHelpProvi        {Default}            DefaultHelpProvider

None     SessionStateProv      {Default}            Providers that produce a view of session state data.

 

 

PS D:\> get-tracesource registryprovider

 

Options   Name                        Listeners            Description

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

None       RegistryProvider     {Default}              The namespace navigation provider for the Windows Registry

 

This command gets all of the Windows PowerShell components that can be traced.

 

PS D:\> get-tracesource

 

Options  Name                             Listeners          Description

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

None      SingleShell                    {Default}            SingleShell

None      MshSnapinLoadUnl         {Default}            Loading and unloading mshsnapins

None      MshConsoleInfo             {Default}            MshConsoleInfo object that is constructed from a console file.

None      PSSnapInInfo                 {Default}            PSSnapInInfo

 

Get-ChildItem

 

This cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the Recurse parameter to get items in all child containers A location can be a file system location, such as a directory, or a location exposed by another provider, such as a registry hive or a certificate store.

 

The -path parameter specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).

 

The -include parameter retrieves only the specified items. Enter a path element or pattern, such as "*.txt".

This parameter is effective only when the command includes the Recurse parameter or the path leads to th   e contents of a directory, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\Windows directory.

 

The -exclude parameter omits the specified items. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

 

The -name parameter retrieves only the names of the items in the locations. If you pipe the output of this command to another command, only the item names are sent.

 

Examples

 

This command gets the child items in the current location. If the location is a file system directory, it gets the    files and sub-directories in the current directory. If the item does not have child items, this command returns to  the command prompt without displaying anything.

 

The default displays lists the mode (attributes), last write time, file size (length), and the name of the file. The valid values for mode are: d (directory), a (archive), r (read-only), h (hidden), and s (system).

 

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--             09-08-2008  08:53:24              Desktop

d-r--             09-08-2008  19:34:21              Documents

d-r--             25-03-2008  12:38:51              Downloads

d-r--             11-08-2008  14:29:19              Favorites

 

This command retrieves all of the .txt files in the current directory and all of the subdirectories. The Include parameter specifies the file name extension. The Recurse parameter directs Windows PowerShell to retrieve objects recursively, and indicates that the subject of the command is the specified directory and its contents.

 

PS D:\Users\bala> get-childitem  -include *.txt -recurse

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala\Desktop\Systems - Training\Courses

 

Mode     LastWriteTime                    Length  Name

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

-a---        07-09-2005  14:58:22       3825     sourcecode.txt

 

    Directory: Microsoft.PowerShell.Core\FileSystem::D:\Users\bala\Desktop\Mahatma\articles

 

Mode     LastWriteTime                    Length  Name

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

-a---        11-12-2007  15:02:00       82690 Who is mahatma?.txt

-a---        11-12-2007  15:44:43       20144 Does Gandhi live now?(1949).txt

-a---        01-12-2007  18:24:39       74229 Are we all Gandhians?.txt

..........

..........

 

This command lists the .txt files in the windows directory, except for those whose names start with the letter M.

 

PS D:\Users\bala> get-childitem c:\windows\*.txt  -exclude m*

 

    Directory: Microsoft.PowerShell.Core\FileSystem::C:\windows

 

Mode     LastWriteTime                    Length  Name

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

-a---        22-11-2007  23:08:28         1924   OEWABLog.txt

-a---        08-01-2008  17:13:28       27686   SchedLgU.Txt

-a---        22-11-2007  23:12:25     666071   setuplog.txt

-a---        22-11-2007  22:31:53            264   UPGRADE.TXT

 

This command retrieves all of the registry keys in the HKEY_LOCAL_MACHINE\SOFTWARE key in the registry of the local  computer.

 

PS D:\Users\bala> get-childitem registry::hklm\software\adobe

 

   Hive: Microsoft.PowerShell.Core\Registry::hklm\software\adobe

 

SKC  VC     Name                           Property

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

  1      0     Acrobat Reader              {}

  1      0     Repair                          {}

 

 

Get-ItemProperty

 

This cmdlet is used to retrieve the properties of a specified item.

 

The -path and -name parameters are used to  specify the path to the item or items and the name of the property or properties to retrieve.

 

Examples

 

This command displays information about the C:\Windows directory.

 

PS D:\Users\bala> get-itemproperty c:\windows

 

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

 

Mode      LastWriteTime               Length      Name

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

d----        13-12-2007  20:03:51                  windows

 

This command gets the properties of the myalias.txt file. The result is piped to the format-list cmdlet to display the output as a list.

 

PS D:\Users\bala> get-itemproperty myalias.txt  | format-list

 

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

Name               : myalias.txt

Length              : 4442

CreationTime   : 03-03-2008 11:53:17

LastWriteTime : 03-03-2008 11:53:17

LastAccessTime : 03-03-2008 11:53:17

VersionInfo          :

 

This command displays the value name and data of each of the registry entries contained in the CurrentVersion registry subkey. 

 

PS D:\Users\bala> get-itemproperty hklm:\software\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

 

This command is same as the above example except that it displays the value name and data of the Config registry entry contained in the Mycompany entry in the registry.

 

PS D:\Users\bala> get-itemproperty hklm:\software\mycompany -name 'config' | format-list 'config'

 

config : 1

 

Get-Content

   

This cmdlet gets the content of the item at the location specified by the path, such as the text in a file. It reads the content one line at a time and returns an object for each line.

The parameter  -path specifies the path to an item and  -totalCount specifies how many lines of content are retrieved.

 

The -readCount is an important parameter that specifies how many lines of content are sent through the pipeline at a time. The default value, 0, sends all of the content at one time.This parameter does not change the content displayed, but it does affect the time it takes to display the content. As the value of ReadCount increases, the time it takes to return the first line increases, but the total time for the operation decreases. This can make a perceptible difference in very large items.

 

Sponsors

Recent Articles

Examples

 

This command displays the content of the myalias.txt file on the console. It uses the Path parameter to specify the name of the item. Get-Content actually passes the content down the pipeline, but because there are no other pipeline elements, the content is formatted and displayed on the console.

 

PS D:\Users\bala> get-content -path 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"

 

This command gets the first 10 lines of the myalias.txt file and stores it in the sample.txt file.

 

PS D:\Users\bala> get-content -path myalias.txt -totalcount 10 | set-content sample.txt

PS D:\Users\bala> type sample.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"

 

Remove-Variable

 

The Remove-Variable cmdlet deletes a variable and its value from the scope in which it is defined, such as the current console. You cannot use this cmdlet to delete variables that are set as constants or those that are owned by the system. Changes to the console affect only the current console, unless you use Export-Console to save the console.

 

The -name parameter specifies the name of the variable to be removed.

 

Examples

 

The following cmdlets create, retrives and removes a variable $fname.

 

PS D:\Users\bala> $fname = "sample.txt"

PS D:\Users\bala> $fname

sample.txt

PS D:\Users\bala> remove-variable fname

 

 

Remove-PSSnapin

 

This cmdlet removes a Windows PowerShell snap-in from the current console. You can use it to remove custom snap-ins that you have added to Windows PowerShell, but you cannot use it to remove the snap-ins that are installed  with Windows PowerShell.

 

After a snap-in is removed, it is still loaded, but the cmdlets and providers that the snap-in supports are no longer available in the console. The changes affect only the current console, unless you use  Export-Console to save the console.

 

The -name parameter indicates the unique-name(s) of the PSSnapIn(s) to remove from the current console file. The  -confirm parameter prompts you for confirmation before executing the command.

 

Examples

 

This command removes the Micrsoft.Exchange snap-in from the current console. When the command completes, the cmdlets and providers that the snap-in supported are not available in the console.

 

PS D:\Users\bala> remove-pssnapinn -name Microsoft.Exchange

 

This command uses the Export-Console command to export the new console configuration to the nosnapin.psc1 file. If you use this console file in Windows PowerShell, removed snap-ins from the console are not loaded.

 

PS D:\Users\bala> Export-console nosnapin.psc1

 

The following cmdlets tries to remove a snap-in that comes with Powershell and it fails.

 

PS D:\Users\bala> remove-pssnapin microsoft.powershell.core

Remove-PSSnapin : Cannot remove the Windows PowerShell snap-in microsoft.powershell.core because it is a system snap-in. Verify the name of the snap-in being removed and try again.

At line:1 char:16

+ remove-pssnapin  <<<< microsoft.powershell.core

 

 

Remove-PSDrive

 

This cmdlet removes a Windows PowerShell drive from its location. When no drive name is specified, all drives exposed by the specified provider are removed. An error will result if the current working location is a container on a drive you are trying to remove.

 

The -name parameter specifies the names of the Windows PowerShell drives to remove. The -psProvider specifies the names of the Windows PowerShell providers. All drives associated with the provider will be removed. You may use the -scope parameter that specifies indices used to identify the scope where the drive will be installed.

 

Examples

 

This example removes a Windows PowerShell drive named "variable". Before removing it from the console, get-psdrive cmdlet lists all the current drives installed.

 

PS D:\Users\bala> get-psdrive

 

Name       Provider         Root

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

Alias         Alias

C               FileSystem     C:\

cert           Certificate       \

D               FileSystem     D:\

Env           Environment

Function   Function

HKCU        Registry         HKEY_CURRENT_USER

HKLM        Registry         HKEY_LOCAL_MACHIN

Variable    Variable

 

PS D:\Users\bala> remove-psdrive variable

 

After the removal of "variable" drive, issue the get-psdrive cmdlet to check if it is removed.

 

PS D:\Users\bala> get-psdrive

 

Name       Provider         Root

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

Alias         Alias

C               FileSystem     C:\

cert           Certificate       \

D               FileSystem     D:\

Env           Environment

Function   Function

HKCU        Registry         HKEY_CURRENT_USER

HKLM        Registry         HKEY_LOCAL_MACHIN

 

Remove-Item

 

This cmdlet deletes one or more items. Because it is supported by many providers, it can delete many different types of items, including files, directories, registry keys, variables, aliases, certificates, and functions.

 

The  -path parameter specifies a path to the items being removed. The -recurse parameter deletes the items in the specified locations and in all child items of the locations.

 

The parameters -force, -include, -exclude, -filter, -credential, -whatif and -confirm may also be used with this cmdlet.

 

Examples

 

This command deletes all of the files with names that include a dot (.) from the d:\bala directory. Because the command specifies a dot, the command does not delete directories, or files with no file name extension.

 

PS D:\Users\bala> remove-item d:\bala\*.*

 

This command deletes from the current directory all files with a .htm file name extension. It uses the wildcard character (*) to specify the contents of the current directory.

 

PS D:\Users\bala> remove-item * -include "*.htm"

 

This command deletes all of the CSV files in the current directory and all subdirectories recursively.

 

PS D:\Users\bala> get-childitem * -include "*.csv" -recurse | remove-item

 

This command deletes the test registry key and all of its subkeys and values.

 

PS D:\Users\bala> remove-item hklm:\software\test

 

Update-FormatData

 

This cmdlet is used to add format files to the format data that it loads in the shell.

 

The Windows PowerShell directory contains several format files. They have the file extension .ps1xml and are text files in XML format.  ou do not need to restart the shell to update the format data. When the shell starts, it reads the format data from those files. You can build your own format.ps1xml files.

 

There are two parameters you may use along with this cmdlet. The -appendPath parameter specify the path to optional format.ps1xml files which will be included in the list of files loaded. These are processed after the built-in files are loaded.

 

The -prependPath specifies the path to optional format.ps1xml files which will be included in the list of files loaded. These fi  les are processed in the order they are specified and before the built-in files are loaded.

 

Examples

 

This command updates the shell format configuration files from the built-in format.ps1xml files.

 

PS D:\Users\bala> update-formatdata

 

This command updates the shell format configuration from the built-in format files and adds format configuration information from two additional files. The Prependpath parameter causes the shell to process the new files before the built-in files.

 

PS D:\Users\bala> update-formatdata-prependpath RedFormat.Ps1xml,GreenFormat.Ps1xml

 

Update-TypeData

 

This cmdlet updates the current extended type configuration by reloading the *.types.ps1xml files into memory. Extended type information is normally loaded when Windows PowerShell requires the type information it contains. This can be used to preload all type information. It is particularly useful when you are developing types and want to load those new types for testing purposes.

 

The -prependPath and  -appendPath parameters specify the paths to the .ps1xml files included in the list of files loaded before and after the built-in files.

 

Examples

 

This example updates the extended type configuration from the *.types.ps1xml files.

 

PS D:\Users\bala> update-typedata

 

This example updates the extended type configuration from the *.types.ps1xml files, processing the myype and myobject files first.

 

PS D:\Users\bala> update-typedata -prependpath mytype.ps1xml, myobject.ps1xml

 

Readers must have a brief idea on what these typedata and .ps1xml files are. Here is an overview:

 

The types.ps1xml file in the PowerShell home directory provides a mechanism for extending the .NET type system. By default, PowerShell adds a number of elements to the file to extend the .NET types. In addition, you can add other elements for your own customizations.

 

One way that a type can be extended is by adding a property. To add a  property (or to extend a type in any way), you must modify the <type>  element for the specific type in the types.ps1xml file. For example,  the array type, by default, does not include a Count property, so PowerShell defines an alias property called Count. The property includes a  reference member name for the Length property, as shown in the following ArrayTotalElementsProperty.ps1xml file:

 

<Types>

        <Type>

            <Name>System.Array</Name>

            <Members>

                <AliasProperty>

                    <Name>TotalElemets</Name>

                    <ReferencedMemberName>

                        Length

                    </ReferencedMemberName>

                </AliasProperty>

            </Members>

        </Type>

</Types>

 

Ensure that the Windows PowerShell runs in the Administrator mode and check if the session has execution of session rights.  The following cmdlet would put the session with unrestricted permissions so as to enable exectuion of .ps1xml files.

 

PS D:\Windows\System32> set-executionpolicy unrestricted

 

This command adds the arraytotalelementsproperty.ps1xml file to the current session type data.

 

PS D:\Windows\System32> update-typedata -appendpath d:\users\bala\arraytotalelementsproperty.ps1xml

 

You can verify the custom AliasProperty by using a Get-Member command to retrieve the properties of an object array, as shown in the following command:

 

PS D:\Windows\System32> get-member -inputobject ('a', 'b', 'c', 'd') -member "AliasProperty"

 

The command returns the following results:

 

   TypeName: System.Object[]

 

Name                  MemberType    Definition

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

Count                 AliasProperty   Count = Length

TotalElements   AliasProperty   TotalElements = Length

 

As you can see, the TotalElements alias property is listed as one of the properties, with a definition of "TotalElements= Length."

 

In addition to modifying the existing types.ps1xml file, you can create your own types.ps1xml file to add type and property definitions or override default type and property definitions. You can then place the new file in any directory in the PowerShell command path. If your file defines a type or property that is already defined, it will replace the  same type or property defined in any instance of types.ps1xml that  occurs in a directory earlier in the command path.

Clear-ItemProperty

 

This cmdlet deletes the value of a property, but it does not delete the property. You can use this cmdlet to delete the data from a registry value.

 

The -path parameter specifies the path to the property being cleared. The -name parameter specifies the name of the property to be cleared, such as the name of a registry value.

 

The paramter -force may be used to overrides restrictions that prevent the command from succeeding, just so the changes do not compromise security. For example, Force will override the read-only attribute or create directories to complete a file path, but it will not attempt to change file permissions.

 

Example

 

This command deletes the data in the testid registry value in the test subkey of KEY_LOCAL_MACHINE\Software\

 

PS D:\Windows\System32> get-itemproperty hklm:\software\test

 

 

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

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

PSChildName : test

PSDrive          : HKLM

PSProvider     : Microsoft.PowerShell.Core\Registry

testid              : 101

 

This command deletes the data in the testid registry value in the test subkey of KEY_LOCAL_MACHINE\Software\.

 

PS D:\Windows\System32> clear-itemproperty hklm:\software\test -name "testid"

 

After deleting value, use get-itemproperty cmdlet to see the property data.

 

PS D:\Windows\System32> get-itemproperty hklm:\software\test

 

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

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

PSChildName  : test

PSDrive           : HKLM

PSProvider      : Microsoft.PowerShell.Core\Registry

testid               :

 

Clear-Variable

 

This command deletes the data stored in an variable, but it does not delete the variable. As a result,  the value of the variable is NULL (empty). If the variable has a specified data or object type, Clear-Variable preserves the type of the object stored in the variable.

 

The -name parameter specifies the name of the variable to be cleared.

You may use the common parameters such as -include, -exclude, -scope, -force, -passThru along with this cmdlet.

 

Example

 

The following three cmdlets creates a new variable 'a' with initial value 345, clears the variable 'a' and check if the value is cleared.

 

PS D:\Windows\System32> $a=345

PS D:\Windows\System32> clear-variable a

PS D:\Windows\System32> $a

 

The following commands demonstrate that clearing a variable in a child scope does not clear the value in the parent scope.

The first command sets the value of the variable $a to 100. The second command uses the invoke operator (&) to run a

Clear-Variable command in a new scope. The variable is cleared in the child scope (although it didn't exist), but it is not cleared in the local scope. The third command, which gets the value of $a, shows that the value 100 is unaffected.

 

PS D:\Windows\System32> $a=100

PS D:\Windows\System32> & {clear-variable a}

PS D:\Windows\System32> $a

100

 

New-Service

 

This cmdlet is used to create a new entry for a Windows Service in the registry and the Service Database. This would allow you to set the display name, description, startup type and dependencies of the service.

 

The  -name parameter specifies the name of the service. The -binaryPathName specifies the path to the executable file for the service. You may use the -displayName and -description parameters for identification and description of the service.The

-startupType parameter sets the startup type of the service;the acceptable values are "Automatic", "Manual" and "Disabled".

 

Example

 

This command creates a new entry in the registry and Service Database for a service named MyService. Note the default status of the service is "Stopped"

 

PS D:\Windows\System32> new-service

 

cmdlet new-service at command pipeline position 1

Supply values for the following parameters:

Name: MyService

BinaryPathName: D:\bala\Arithmetic\Arithmetic\bin\Debug\arithmetic.dll

 

Status     Name               DisplayName

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

Stopped  MyService          MyService

 

 

 

New-PSDrive

 

This cmdlet installs a new drive at the specified location and within the specified parameters.

 

You may specify the name of the new drive using the -name parameter and name of the provider using the -psProvider parameter.

 

The -root parameter specifies the provider internal root or path for the drive being added.

 

A short description of the drive may be specified using the -description parameter.

 

Example

 

This example installs the myDrive on the file system provider. The drive will be assigned the name myDrive. The drive will be rooted at "d:\myProvider"

 

PS D:\Users\bala> new-psdrive -name mydrive -psprovider filesystem -root d:\myprovider

 

Name        Provider        Root                        CurrentLocation

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

mydrive    FileSystem    D:\myprovider

 

Move-Item

 

This cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider. For example, it can move a file or subdirectory from one directory to another or move a registry subkey from one key to another. When you move an item, it is added to the new location and deleted from its original location.

 

The -path parameter specifies the path to the current location of the items. The -destination specifies the path to the location where the items are being moved.  To rename the item being moved, specify a new name in the value of Destination.

 

The common parameters such as -include, -exclude, -filter, -force, -passthru, -literalpath and -credential may also be specified.

 

Example

 

This command moves the bb.txt file from the current folder to the D:\Temp directory and renames it  to "test.txt".

 

PS D:\Users\bala> move-item bb.txt d:\temp\test.txt

PS D:\Users\bala> ls d:\temp

 

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

 

Mode       LastWriteTime               Length  Name

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

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

-a---        03-10-2008  18:06:47        1037    COMMANDS.txt

-a---        03-10-2008  18:40:11      44187    house.jpg

 

This command moves all of the text files from the current directory and all subdirectories to d:\TextFiles directory. It uses the Get-Childitem cmdlet to get all of the child items in the current directory represented by the dot (.)) and its subdirectories that have a *.txt file name extension. It uses the Include parameter to limit the retrieval to *.txt files.

 

PS D:\Users\bala> gci . -include *.txt | move-item -dest d:\textfiles

 

 

Split-Path

 

This cmdlet returns only the specified path of a path, such as the parent directory, a child directory, or a file name. You can use this cmdlet to display or submit only a selected part of a path in a script or application.

 

Use the -path parameter to specify the paths to be split and the -qualifier parameter returns only the qualifier of the specified path. For the FileSystem or registry providers, the qualifier is the drive of the provider path, such as C: or HKCU:.

 

The -parent parameter returns only the parent containers of the item or container specified by the path. For example, in the path "C:\Test\Logs\Pass1.log", it returns "C:\Test\Logs". Parent is the default split location parameter.

 

The -leaf parameter returns only the last item or container in the path. For example, in the path "C:\Test\Logs\Pass1.log", it returns only "Pass1.log".

 

The -noQualifier parameter returns the path without the qualifier. For the FileSystem or registry providers, the qualifier is the drive of the provider path, such as C: or HKCU:. For example, in the path  "C:\Test\Logs\Pass1.log", it returns only "\Test\Logs\Pass1.log".

 

The -isAbsolute parameter returns TRUE if the path is absolute and FALSE if it is relative. An absolute path has a length greater than zero and does not use "." to indicate the current path.

 

The -resolve parameter displays the items that are referenced by the path that remains after the split.

 

Examples

 

This command returns only the qualifier (the drive) of the path.

 

PS D:\Users\bala> split-path "hkcu:\software\microsoft" -qualifier

 

hkcu:

 

The following commands displays the files that are referenced by the split path.  It uses the -leaf and -resolve parameters to get different results.

 

PS D:\Users\bala> split-path "d:\users\bala\*.txt" -leaf -resolve

commands.txt

PS D:\Users\bala> split-path "d:\users\bala\*.txt" -leaf

*.txt

PS D:\Users\bala> split-path "d:\users\bala\*.txt" -resolve

D:\users\bala

 

This command determines if the path is relative or absolute. In this case, because the path is relative to the current directory, which is represented by a dot (.), it returns FALSE ($false).

 

PS D:\Users\bala> split-path ".\*.txt" -isabsolute

 

False

 

Add-Member

 

This cmdlet adds a user-defined custom member to an instance of a Windows PowerShell object. It lets you add the following types of members: AliasProperty, CodeProperty, NoteProperty, ScriptProperty,PropertySet,CodeMethod,MemberSet and ScriptMethod.

 

You set the initial value of the member by using the Value parameter. In the case of AliasProperty, ScriptProperty, CodeProperty and CodeMethod, you can supply additional information by using the SecondValue parameter.

 

The additional members are added to the particular instance of the object that you pipe to add-member or specify using the InputObject parameter. The additional member is only available while that instance exists. You can use the Export-Clixml cmdlet to save the instance, including the additional members, to a file. The information stored in that file can be used by the Import-Clixml cmdlet to recreate the instance of the object.

 

The parameters commonly used with this cmdlet are -inputObject, -memberType, -name and -value. The -secondValue parameter specifies additional information.

 

Examples

 

This command adds a note property to a DirectoryInfo object returned by Get-ChildItem. It names the new property status and assigns it a value of done. The last line of the command pipes the updated object to Get-Member to demonstrate that the property has been added.

 

PS D:\Users\bala> $a = (get-childitem)[0]

PS D:\Users\bala> $a | add-member -membertype noteproperty -name status -value Completed

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

 

 

   TypeName: System.IO.DirectoryInfo

 

Name                    MemberType     Definition

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

....

....

status                    NoteProperty     System.String status=Completed

....

....

 

This command adds a script method to a string object. The script method exposes the Split() method of the System.String .Net Framework Class Library class to  return the individual words in a string by calling a method named words on the string object. Note that the Passthru parameter was specified to force Add-Member to return the extended string object as output to be stored in the $a variable.

 

PS D:\Users\bala> $a="this is a string"

PS D:\Users\bala> $a=add-member -inputobject $a -membertype scriptmethod -name words -value {$this.split()} -passthru

PS D:\Users\bala> $a.words()

this

is

a

string

 

Previous