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- Part 2
Author: balamurali balaji

This tutorial is brought to you by BB Systems.

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


Previous||Next

ForEach-Object

 

This cmdlet performs an operation against each of a set of input objects. The input objects can be piped to the cmdlet or specified by using the InputObject parameter. The operation to perform is described within a script block which is provided to the cmdlet as the value of the Process parameter. The script block can contain any Windows PowerShell script.   Within the script block, the current input object is represented by the $_ variable.

 

In addition to the script block that describes the operations to be carried out on each input object, you can provide two additional script blocks. One, specified as the value of the Begin parameter, runs before the first input object is processed. The other, specified as the value of the End parameter, runs after the last input object is processed.

 

The results of the evaluation of all the script blocks, included the ones specified with Begin and End, are passed down the pipeline.

 

Examples :

 

This command accepts an array of integers, divides each one of them by 10, and displays the results.

 

PS D:\Windows\System32> 300,400,4500 | foreach-object -process {$_/10}

30

40

450

 

 

This command retrieves the files with .txt extension in the newfolder directory and returns and displays the name of each of them.

 

PS D:\users\bala> get-childitem newfolder\*.txt  | foreach-object -process {$_.name}

bb.txt

data.txt

data1.txt`

data2.txt

pay.txt

_topics.txt

ps.txt

upstrack.txt

vce.txt

vs.netVSvb6.txt

 

 

This command retrieves the 10 most recent events from the application log and stores them in the $events variable. It then pipes the events to the ForEach-Object cmdlet. The Begin parameter displays the current date and time. Next, the Process parameter uses the Out-File cmdlet to create a text file named events.txt and stores the source property of each of the events in that file. Last, the End parameter is used to display the date and time after all of the processing has completed.

 

PS D:\users\bala> $myevents = get-eventlog -logname application  -newest 10

PS D:\users\bala> $myevents | foreach-object -begin {get-date} -process {out-file -filepath myevents.txt -append -inputobject $_.source} -end {get-date}

 

08 March 2008 11:18:00

08 March 2008 11:18:01

 

 

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

RasClient

Application Error

RasClient

RasClient

RasClient

RasClient

RasClient

SecurityCenter

Desktop Window Manager

Wlclntfy

 

 

 

Get-Member

 

This cmdlet returns information about objects or collections of objects. You can use the MemberType parameter to specify the type of members you want information about.

 

If you pipeline input to Get-Member, it outputs a MemberDefinition object for each distinct type of input object.

If you supply input by using the InputObject parameter it returns a single MemberDefinition object that represents either the single input object or the collection class that contains the set of input objects.

 

The name parameter specifies the member names to retrieve information about.

The -inputObject parameter specifies the objects to retrieve information about.

The -memberType paramter may take one of the valid type of members listed here: AliasProperty, CodeProperty, Property, NoteProperty,ScriptProperty, Properties, PropertySet, Method, CodeMethod, ScriptMethod, Methods, ParameterizedProperty, MemberSet, and All.

 

Examples :

 

The following command uses get-childitem that returns list of folders and files in the current directory. Sending this as input to the get-member cmdlet and retrieving property information would yield properties of both folder and file types.

 

PS D:\Users\bala> get-childitem | get-member -membertype  property

 

   TypeName: System.IO.DirectoryInfo

 

Name                MemberType Definition

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

Attributes             Property   System.IO.FileAttributes Attributes {get;set;}

CreationTime       Property   System.DateTime CreationTime {get;set;}

CreationTimeUtc   Property   System.DateTime CreationTimeUtc {get;set;}

Exists                  Property   System.Boolean Exists {get;}

Extension             Property   System.String Extension {get;}

FullName              Property   System.String FullName {get;}

LastAccessTime     Property   System.DateTime LastAccessTime {get;set;}

LastAccessTimeUtc Property   System.DateTime LastAccessTimeUtc {get;set;}

LastWriteTime       Property   System.DateTime LastWriteTime {get;set;}

LastWriteTimeUtc   Property   System.DateTime LastWriteTimeUtc {get;set;}

Name                   Property   System.String Name {get;}

Parent                  Property   System.IO.DirectoryInfo Parent {get;}

Root                     Property   System.IO.DirectoryInfo Root {get;}

 

 

   TypeName: System.IO.FileInfo

 

Name              MemberType Definition

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

Attributes             Property   System.IO.FileAttributes Attributes {get;set;}

CreationTime        Property   System.DateTime CreationTime {get;set;}

CreationTimeUtc   Property   System.DateTime CreationTimeUtc {get;set;}

Directory              Property   System.IO.DirectoryInfo Directory {get;}

DirectoryName      Property   System.String DirectoryName {get;}

Exists                  Property   System.Boolean Exists {get;}

Extension             Property   System.String Extension {get;}

FullName             Property   System.String FullName {get;}

IsReadOnly          Property   System.Boolean IsReadOnly {get;set;}

LastAccessTime     Property   System.DateTime LastAccessTime {get;set;}

LastAccessTimeUtc Property   System.DateTime LastAccessTimeUtc {get;set;}

LastWriteTime       Property   System.DateTime LastWriteTime {get;set;}

LastWriteTimeUtc   Property   System.DateTime LastWriteTimeUtc {get;set;}

Length                  Property   System.Int64 Length {get;}

Name                   Property   System.String Name {get;}

 

This command displays information about the AliasInfo object that is returned by the Get-Alias cmdlet.

PS D:\Users\bala> $myalias = get-alias

PS D:\Users\bala> get-member -inputobject $myalias

 

   TypeName: System.Object[]

 

Name               MemberType    Definition

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

Count               AliasProperty Count = Length

Address            Method        System.Object& Address(Int32 )

Clone               Method        System.Object Clone()

CopyTo             Method        System.Void CopyTo(Array array, Int32 index), System.Void CopyTo(Array array, Int64...

Equals               Method        System.Boolean Equals(Object obj)

Get                   Method        System.Object Get(Int32 )

GetEnumerator   Method        System.Collections.IEnumerator GetEnumerator()

GetHashCode     Method        System.Int32 GetHashCode()

GetLength          Method        System.Int32 GetLength(Int32 dimension)

GetLongLength   Method        System.Int64 GetLongLength(Int32 dimension)

GetLowerBound   Method        System.Int32 GetLowerBound(Int32 dimension)

GetType             Method        System.Type GetType()

GetUpperBound   Method        System.Int32 GetUpperBound(Int32 dimension)

GetValue            Method        System.Object GetValue(Params Int32[] indices), System.Object GetValue(Int32 index)...

get_IsFixedSize   Method        System.Boolean get_IsFixedSize()

get_IsReadOnly   Method        System.Boolean get_IsReadOnly()

get_IsSynchronized Method        System.Boolean get_IsSynchronized()

get_Length             Method        System.Int32 get_Length()

get_LongLength       Method        System.Int64 get_LongLength()

get_Rank                Method        System.Int32 get_Rank()

get_SyncRoot           Method        System.Object get_SyncRoot()

Initialize                  Method        System.Void Initialize()

Set                          Method        System.Void Set(Int32 , Object )

SetValue                   Method        System.Void SetValue(Object value, Int32 index), System.Void SetValue(Object value,...

ToString            Method        System.String ToString()

IsFixedSize        Property      System.Boolean IsFixedSize {get;}

IsReadOnly       Property      System.Boolean IsReadOnly {get;}

IsSynchronized  Property      System.Boolean IsSynchronized {get;}

Length             Property      System.Int32 Length {get;}

LongLength      Property      System.Int64 LongLength {get;}

Rank               Property      System.Int32 Rank {get;}

SyncRoot         Property      System.Object SyncRoot {get;}

 

The following cmdlet brings only method information from AliasInfo object.

PS D:\Users\bala> get-member -inputobject $myalias -membertype method

 

   TypeName: System.Object[]

 

Name               MemberType Definition

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

Address            Method     System.Object& Address(Int32 )

Clone               Method     System.Object Clone()

CopyTo             Method     System.Void CopyTo(Array array, Int32 index), System.Void CopyTo(Array array, Int64 in...

Equals              Method     System.Boolean Equals(Object obj)

Get                  Method     System.Object Get(Int32 )

GetEnumerator  Method     System.Collections.IEnumerator GetEnumerator()

GetHashCode    Method     System.Int32 GetHashCode()

GetLength         Method     System.Int32 GetLength(Int32 dimension)

GetLongLength  Method     System.Int64 GetLongLength(Int32 dimension)

GetLowerBound  Method     System.Int32 GetLowerBound(Int32 dimension)

GetType            Method     System.Type GetType()

GetUpperBound  Method     System.Int32 GetUpperBound(Int32 dimension)

GetValue           Method     System.Object GetValue(Params Int32[] indices), System.Object GetValue(Int32 index), S...

get_IsFixedSize  Method     System.Boolean get_IsFixedSize()

get_IsReadOnly  Method     System.Boolean get_IsReadOnly()

get_IsSynchronized Method     System.Boolean get_IsSynchronized()

get_Length            Method     System.Int32 get_Length()

get_LongLength     Method     System.Int64 get_LongLength()

get_Rank              Method     System.Int32 get_Rank()

get_SyncRoot        Method     System.Object get_SyncRoot()

Initialize               Method     System.Void Initialize()

Set                       Method     System.Void Set(Int32 , Object )

SetValue               Method     System.Void SetValue(Object value, Int32 index), System.Void SetValue(Object value, In...

ToString                Method     System.String ToString()

 

 

 

Clear-Item

 

 

The Clear-Item cmdlet deletes the value of an item, but does not delete the item. For example, Clear-Item can delete the value of a variable, but it does not delete the variable. The value that used to represent a cleared item is defined by each Windows PowerShell provider.  Clear-Item is similar to Clear-Content, but works on aliases and variables, instead of files.

 

The -path parameter specifies the path to the items being cleared.

 

Examples :

 

This command deletes the value of the variable, zipcode, created in the previous blog.The variable remains and is valid, but its value is set to null.

 

PS D:\Users\bala> clear-item variable:zipcode

PS D:\Users\bala> $zipcode

 

The variable name is prefixed with "Varible:" to indicate the PowerShell Variable provider.

 

Optionally, you can switch to the PowerShell Variable provider namespace first and then perform the Clear-Item command.

 

PS D:\Users\bala> set-location variable:

PS Variable:\> $noofdays

100

PS Variable:\> clear-item noofdays

PS Variable:\> $noofdays

 

This command deletes all registry entries in the mycompany key, but only after prompting you to confirm your intent.Here again, the registry entry is not removed, instead it is initialized.

 

PS D:\Windows\System32> clear-item registry::hklm\software\mycompany -confirm

 

Confirm

Are you sure you want to perform this action?

Performing operation "Clear Item" on Target "Item: hklm\software\mycompany".

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

PS D:\Windows\System32> get-item hklm:\software\m*

 

 

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

 

SKC  VC Name                           Property

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

  2   0 Macromedia                     {}

174 0 Microsoft                          {}

  1   0 Motorola                          {}

  1   0 Mozilla                             {}

  5   0 MozillaPlugins                   {}

  0   0 Mycompany                      {}

 

 

New-Variable

 

This cmdlet creates a new variable. It does not, by default, assign a value to the variable.

 

The parameter -name specifies the name of the new variable; -value, the initial value assigned to the variable; -scope parameter takes one of the values: "global", "local", or "script"; -description specifies the user-supplied description of the variable;

 

You may also create ReadOnly variables, Constant or Private variables by specifying them in the -option parameter.  Any combination of these may be given.

    

Examples :

 

This command creates a new variable named noofdays. It has no value immediately following the command.Later the value 100 is assigned to it.

 

PS D:\Users\bala> new-variable  noofdays

PS D:\Users\bala> $noofdays = 100

 

This command creates a variable named zipcode and assigns it the value 98033.

 

PS D:\Users\bala> new-variable zipcode -value 98033

PS D:\Users\bala> $zipcode

98033

 

 

 

New-Object

 

This cmdlet creates an instance of a .Net or COM object. You specify either the type of a .Net class or a Programmatic Identifier (ProgID) of a COM object. By default, you type the fully-qualified name of a .Net class and the cmdlet returns a reference to an instance of that class. To create an instance of a COM object, use the ComObject parameter and specify the ProgID of the object as its value.

 

The -typeName parameter specifies the fully-qualified name of the .Net The -comObject parameter specifies the programmatic Identifier (ProgID) of the COM object.You cannot specify both the TypeName parameter and the ComObject parameter.

 

The -argumentList specifies a list of arguments to pass to the constructor of the .Net class. Separate elements in the list by using commas (,).

 

Examples :

 

This command creates a .Net object of type System.Version, using the string "1.2.3.4" as the constructor. It stores a reference to the object in the $ver variable and pipes it to the Get-Member cmdlet to display the properties and methods of the referenced object.

 

PS D:\users\bala> $ver = new-object -typename System.Version -argumentlist "1.2.3.4"

PS D:\users\bala> $ver | get-member

 

 

   TypeName: System.Version

 

Name              MemberType Definition

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

Clone             Method         System.Object Clone()

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

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

GetHashCode  Method       System.Int32 GetHashCode()

GetType          Method      System.Type GetType()

get_Build         Method      System.Int32 get_Build()

get_Major         Method      System.Int32 get_Major()

get_MajorRevision Method     System.Int16 get_MajorRevision()

get_Minor             Method     System.Int32 get_Minor()

get_MinorRevision Method     System.Int16 get_MinorRevision()

get_Revision        Method     System.Int32 get_Revision()

ToString              Method     System.String ToString(), System.String ToString(Int32 fieldCount)

Build                  Property   System.Int32 Build {get;}

Major                 Property   System.Int32 Major {get;}

MajorRevision     Property   System.Int16 MajorRevision {get;}

Minor                 Property   System.Int32 Minor {get;}

MinorRevision     Property   System.Int16 MinorRevision {get;}

Revision             Property   System.Int32 Revision {get;}

 

This command creates an instance of the COM object that represents the Internet Explorer application. It uses the object to navigate to a picture fileand then sets the visible property of the object to $true to make the application visible.

 

PS D:\users\bala> $ie = new-object -comobject InternetExplorer.Application

PS D:\users\bala> $ie.visible = $true

PS D:\users\bala> $ie.navigate2("d:\users\bala\pictures\img4.jpg")

 

The command uses the ComObject parameter to create a COM object with the ProgID, "Shell.Application". It stores the resulting reference to the object in the $objShell variable and pipes that variable to the Get-Member cmdlet. The  Get-Member cmdlet displays information about the properties and methods of the COM object. In the last line, the ToggleDesktop method of the object is called. It minimizes all of the open windows on your desktop.

 

PS D:\users\bala> $objshell = new-object -comobject "Shell.Application"

PS D:\users\bala> $objshell | get-member

 

PS D:\users\bala> $objshell.ToggleDesktop()

 

 

   TypeName: System.__ComObject#{866738b9-6cf2-4de8-8767-f794ebe74f4e}

 

Name                 MemberType Definition

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

AddToRecent            Method     void AddToRecent (Variant, string)

BrowseForFolder        Method     Folder BrowseForFolder (int, string, int, Variant)

CanStartStopService  Method     Variant CanStartStopService (string)

CascadeWindows       Method     void CascadeWindows ()

ControlPanelItem     Method      void ControlPanelItem (string)

EjectPC              Method      void EjectPC ()

Explore              Method      void Explore (Variant)

ExplorerPolicy     Method      Variant ExplorerPolicy (string)

FileRun              Method     void FileRun ()

FindComputer     Method     void FindComputer ()

FindFiles            Method      void FindFiles ()

FindPrinter         Method      void FindPrinter (string, string, string)

GetSetting         Method      bool GetSetting (int)

GetSystemInformation Method     Variant GetSystemInformation (string)

Help                   Method     void Help ()

IsRestricted         Method     int IsRestricted (string, string)

IsServiceRunning  Method    Variant IsServiceRunning (string)

MinimizeAll          Method     void MinimizeAll ()

NameSpace         Method     Folder NameSpace (Variant)

Open                  Method     void Open (Variant)

RefreshMenu       Method     void RefreshMenu ()

ServiceStart         Method     Variant ServiceStart (string, Variant)

ServiceStop         Method     Variant ServiceStop (string, Variant)

SetTime              Method     void SetTime ()

ShellExecute        Method     void ShellExecute (string, Variant, Variant, Variant, Variant)

ShowBrowserBar    Method     Variant ShowBrowserBar (string, Variant)

ShutdownWindows Method     void ShutdownWindows ()

Suspend              Method     void Suspend ()

TileHorizontally     Method     void TileHorizontally ()

TileVertically         Method     void TileVertically ()

ToggleDesktop     Method     void ToggleDesktop ()

TrayProperties      Method     void TrayProperties ()

UndoMinimizeALL  Method     void UndoMinimizeALL ()

Windows              Method     IDispatch Windows ()

WindowsSecurity   Method     void WindowsSecurity ()

WindowSwitcher    Method     void WindowSwitcher ()

Application           Property   IDispatch Application () {get}

Parent                 Property   IDispatch Parent () {get}

 

 

 

 

Where-Object

 

It creates a filter that controls which objects will be passed along a command pipeline. It filters objects passed to it as pipelined input or objects provided as the value of the InputObject parameter. It determines which objects to pass along the pipeline by evaluating a script block that may include a reference to an object being filtered. If the result of the evaluation is True, the object being processed is passed along the pipeline; otherwise, the object is discarded.

 

The -filterScript parameter specifies the script block to evaluate in determining which input objects will be passed along the command pipeline. The  -inputObject specifies the objects to be filtered. If you save the output of a command in a variable, you can use InputObject to pass the variable to Where-Object. However, typically, the InputObject parameter is not typed in the command. Instead, when you pass an object through the pipeline, Windows PowerShell associates the passed object with the InputObject parameter.

 

Examples :

 

This command gets a list of all services that are currently stopped.

 

PS D:\users\bala> get-service | where-object {$_.status -eq "stopped"}

 

Status     Name                DisplayName

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

Stopped  ALG                    Application Layer Gateway Service

Stopped  AppMgmt            Application Management

Stopped  aspnet_state       ASP.NET State Service

Stopped  AxInstSV             ActiveX Installer (AxInstSV)

Stopped  CertPropSvc         Certificate Propagation

Stopped  clr_optimizatio...   Microsoft .NET Framework NGEN v2.0....

Stopped  COMSysApp          COM+ System Application

 

This command lists processes that have a working set greater than  25000K. The value of the workingset property is stored in bytes, so the 25000 is multiplied by 1024.

 

PS D:\users\bala> get-process | where-object {$_.workingset -gt 25000*1024}

 

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

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

    467       9          52464      47776   172    21.55   3880 powershell

    790      18         37408      30220   121    20.39   1056 svchost

 

This command gets the processes with a ProcessName property that begins with a letter w. The match operator enables you to use regular expressions within a where clause.

 

PS D:\users\bala> get-process | where-object { $_.ProcessName -match "^w.*" }

 

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

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

    100       4          1268         56        26     0.27    572    wininit

    125       3          1824        324       31     1.13    792    winlogon

    609      25         33448      12816   163    22.00   2060  wmplayer

    328      11         7896       7660       92     0.97    748    wmpnetwk

    108       4          1860       3628       35     0.16   3988   wmpnscfg

    141       3          2780        220        45     0.33    268    wuauclt

     61        3          2772        256        45     0.80   1512   wweb32

 

 

Sponsors

Recent Articles

 

get-process

 

This cmdlet is used to retrieve a process object for each process. If you do not supply any parameters, "Get-Process" gets all of t he processes on the computer, as though you typed "Get-Process *".

 

You can also identify a particular process by process name or process ID (PID), or pass a process object through the pipeline to Get-Process.

 

Examples:

 

The commands below lists all the processes or a single process by name or id.

 

PS D:\Users\bala> get-process wininit

 

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

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

 

     98            4         1256               76      26                   516 wininit

 

 

PS D:\Users\bala> get-process w*

 

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

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

 

     98               4     1256             76       26                    516 wininit

    125              3     1884             76       31                    764 winlogon

    278              8     6808          2288       81                  3088 wmpnetwk

    106              3     1720            932       33         0.08   1376 wmpnscfg

    140              3     2592          1036       44         0.33   1624 wuauclt

     56               3     2576           268       44          1.56  1380 wweb32

 

PS D:\Users\bala> get-process -id (932)

 

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

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

 

   390              11      30332         1456    542                   932 sqlservr

 

convertto-securestring

 

This cmdlet converts plain text or encrypted standard strings into secure strings. It is used with the cmdlets ConvertFrom-SecureString and Read-Host.

 

The secure string created by the cmdlet can be used with cmdlets or functions that require a parameter of type SecureString or can be stored it in a file for later use. The secure string can be converted back to an encrypted, standard string using the ConvertFrom-SecureString cmdlet.

 

You need to supply the value for the -string parameter that specifies the string to be converted into a secure string. The -secureKey and -key parameters are used to convert a secure string into an encrypted standard string. Valid key lengths are 16, 24, and 32 bytes.

 

 

Examples:

 

This command converts the plain text string "pass@word1" into a secure string and stores the result in

the $pwd variable. To use the AsPlainText parameter, the command must also include the Force parameter.

 

PS D:\Users\bala> $pwd = convertto-securestring "pass@word1" -asplaintext -force

PS D:\Users\bala> $pwd

System.Security.SecureString

 

get-psdrive

 

This cmdlet retrieves information about Windows PowerShell drives. You may specify the drive, if required to get the information for a particular drive.

 

Examples:

 

PS D:\Users\bala> get-psdrive

 

Name       Provider      Root                             CurrentLocation

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

 

Alias       Alias

C           FileSystem    C:\

cert        Certificate      \

D           FileSystem    D:\                                Users\bala

E           FileSystem     E:\

Env        Environment

F           FileSystem     F:\

Function Function

G           FileSystem    G:\

HKCU     Registry        HKEY_CURRENT_USER

HKLM     Registry        HKEY_LOCAL_MACHINE

Variable Variable

 

As you notice, Windows PowerShell exposes 7 providers as drives and they are explained below:

 

Alias : The Windows PowerShell Alias provider lets you get, add, change, clear, and delete aliases in Windows PowerShell.

 

    An alias is an alternate name or nickname for a cmdlet, function, or executable file. Windows PowerShell comes with  a set of built-in aliases, and you can add your own aliases to the current console and to your Windows PowerShell profile.The Alias provider is a flat namespace that consists only of the alias objects. The aliases have no child items.

 

    Each alias is an instance of the System.Management.Automation.AliasInfo class.

 

    The Alias provider exposes its data store in the Alias: drive. To work with aliases, you can change your location to the Alias: drive ("set-location alias:") or work from any other Windows PowerShell drive. To reference an alias from another location, use the drive name, "Alias:" in the path.

 

Certificate : The Windows PowerShell Certificate provider lets you navigate through the certificate namespace and view the certificate stores and certificates. It also lets you copy, move, and delete certificates and certificate stores, and open the Certificates snap-in to the Microsoft Management Console (MMC).

 

    The Certificate provider exposes the certificate name space as the Cert: drive in Windows PowerShell. The Cert: drive has the following three levels:

 

    --  Store locations (Microsoft.PowerShell.Commands.X509StoreLocation), which are high-level containers to group the certificates for the current user and all users. Each system as a CurrentUser and LocalMachine (all users) store location.

 

    -- Certificates stores (System.Security.Cryptography.X509Certificates.X509Store), which are physical stores in which certificates are saved and managed.

 

    -- x509 Certificates (System.Security.Cryptography.X509Certificates.X509Certificate2), each of which represent an x509 certificate on the computer. Certificates are identified by their thumbprints.

 

Environment : The Windows PowerShell Environment provider lets you get, add, change, clear, and delete Windows environment variables in Windows PowerShell.

 

    The Environment provider is a flat namespace that consists only objects representing the environment variables. The variables have no child items.

 

    Each environment variable is an instance of the System.Collections.DictionaryEntry class. The name of the variable is the dictionary key and the value of the environment variable is the dictionary value.

 

    The Environment provider exposes its data store in the Env: drive. To work with environment variables, you can change your location to the Env: drive ("set-location env:") or work from any other Windows PowerShell drive. To reference an environment variable from another location, use the drive name, "Env:" in the path.

 

    Changes to the environment variables affect the current console only. To save the changes, add the changes to the Windows PowerShell profile, or use Export-Console to save the current console.

 

 

Function : The Windows PowerShell Function provider lets you get, add, change, clear, and delete functions and filters in Windows PowerShell.

 

   A function is a named block of code that performs an action. When you type the function name, the code in the function runs. A filter is named block of code that establishes conditions for an action. You can type the name of the filter in place of the condition, such as in a Where-Object command.

 

   The Function provider is a flat namespace that consists only of the function and filter objects. Neither functions  nor filters have child items.

 

   Each function is an instance of the System.Management.Automation.FunctionInfo class. Each filter is an instance of the System.Management.Automation.FilterInfo.

 

   The Function provider exposes its data store in the Function: drive. To work with functions, you can change your location to the Function: drive ("set-location function:") or work from any other Windows PowerShell drive. To reference a function from another location, use the drive name, "Function:" in the path.

 

   All changes to the functions affect the current console only. To save the changes, add the function to the Windows PowerShell profile, or use Export-Console to save the current console.

 

 

Variable : The Windows PowerShell Variable provider lets you get, add, change, clear, and delete Windows PowerShell variables in the current console.

 

    The Windows PowerShell Variable provider supports the variables that Windows PowerShell creates, including the automatic and preference variables, and the variables that you create.

 

    The Variable provider is a flat namespace that consists only of the variable objects. The variables have no child items.

 

    Most of the variables are instances of the System.Management.Automation.PSVariable class. However, there are some variations. For example, the "?" variable is a member of the QuestionMarkVariable class and the "MaximumVariableCount" variable is a member of the SessionStateCapacityVariable class.

 

    The Variable provider exposes its data store in the Variable: drive. To work with variables, you can change your location to the Variable: drive ("set-location variable:") or work from any other Windows PowerShell drive. To reference an variable from another location, use the drive name, "Variable:" in the path.

 

 

Registry : The Windows PowerShell Registry provider lets you get, add, change, clear, and delete registry keys and values in Windows PowerShell.

 

    Registry keys are represented as instances of the Microsoft.Win32.RegistryKey class. Registry values are represented as PSCustomObject instances.

 

    The Registry provider lets you access a hierarchical namespace that consists of registry keys and subkeys. Registry values and data are not components of that hierarchy. Instead, they are properties of each of the keys.

 

    Each registry key is protected by a security descriptor. You can use Get-Acl to view the security descriptor of a key.

 

FileSystem : The Windows PowerShell FileSystem provider lets you get, add, change, clear, and delete files and directories in Windows PowerShell.. A Windows PowerShell Provider acts as an interface between WIndows PowerShell and a data store.

    In this case, the data store is a hierarchical collection of files and directories. The use of the FileSystem provider enables you to access the files and directories as you would any data store accessible through a Windows PowerShell Provider. As a result, you can use the same set of core cmdlets from one provider to the next, presenting you with a common experience among the various providers and reducing the time it takes to use a new provider.

 

    The FileSystem provider exposes Windows PowerShell drives that correspond to the logical drives configured on your  computer, including drives mapped to network shares.

 

 

The following command displays information about drives with names that begin with the letters HK.

 

PS D:\Users\bala> get-psdrive HK*

 

Name       Provider      Root                               CurrentLocation

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

HKCU       Registry      HKEY_CURRENT_USER

HKLM       Registry      HKEY_LOCAL_MACHINE

 

 

 

set-content

 

The Set-Content cmdlet is a string-processing cmdlet that writes or replaces the content in the specified item, such as a file. You may type the content in the command or send content through the pipeline to Set-Content.

 

The parameters mainly used in this cmdlet are  -path(location for the specified item), -include(pattern for replace criteria), -exclude(pattern for omission criteria), and -value(new content for the item).The -passThru parameter value passes the object created by this cmdlet through the pipeline.

 

Examples :

 

 

This command replaces the content of data.txt in the documents directory with the given value.

 

PS D:\Users\bala> set-content -path documents\data.txt -value "This cmdlet works with the FileSystem provider"

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

This cmdlet works with the FileSystem provider

 

This command creates a text file that contains only the current date and time. It uses the Get-Date cmdlet to get the current system date and time. The pipeline operator passes the result to Set-Content, which creates the file and writes the content.

 

PS D:\Users\bala> get-date | set-content data1.txt

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

25-02-2008 16:11:18

 

 

This command replaces all instances of "and" with "&" symbol in the data2.txt file. It uses the Get-Content cmdlet to get the content of data2.txt. The pipeline operator sends the results to the ForEach-Object cmdlet, which applies the expression to each line of content in Get-Content. The expression uses the "$_" symbol to refer to the current item and the Replace parameter to

specify the text to be replaced. Another pipeline operator sends the changed content to Set-Content which replaces the text in data2.txt with the new content.

 

The parantheses around the Get-Content command assure that the Get operation is complete, before the Set operation begins. Otherwise, command will fail because the two functions will be trying to access the same file.

 

PS D:\Users\bala\Documents> type data2.txt

C# and .NET Framework 2.0v, 3.0v

ASP.NET 2.0v and AJAX

SQL Server 2k and 2k5 new features

XML, XPATH XSL and XSD

Object-Oriented Design and Analysis

Design Patterns

Unified Modeling Language

RDBMS concepts

WebServices and Remoting

Advanced Excel and VBA

Windows PowerShell

 

 

PS D:\Users\bala\Documents> (get-content data2.txt) | foreach-object {$_ -replace "and", "&"} | set-content data2.txt

 

 

PS D:\Users\bala\Documents> type data2.txt

C# & .NET Framework 2.0v, 3.0v

ASP.NET 2.0v & AJAX

SQL Server 2k & 2k5 new features

XML, XPATH XSL & XSD

Object-Oriented Design & Analysis

Design Patterns

Unified Modeling Language

RDBMS concepts

WebServices & Remoting

Advanced Excel & VBA

Windows PowerShell

 

 

push-location

 

The Push-Location cmdlet pushes the current location onto a default stack or onto a stack that you create. If you specify a path, Push-Location pushes the current location onto the stack, and then changes to the location specified by the path. You cannot push a location onto the stack unless it is the current location.

 

The -path is an optional parameter that specify the location to which you want to change;  -stackName specifies the name of a stack. The current location is pushed onto this stack, and this stack becomes the current stack. If the stack does not yet exist, it is created.

 

Examples:

 

    This command pushes the current location onto the default stack and then changes the location to C:\Windows.

 

PS D:\users\bala> push-location c:\windows

PS C:\WINDOWS>

 

    This command pushes the current location onto the RegFunction stack and changes to the HKLM:\Software\Policies location. This command shows that you can use Push-Location with the Windows PowerShell registry provider.

 

 

PS D:\users\bala> push-location hklm:\software\policies -stackname registryfunc

PS HKLM:\software\policies> dir

 

 

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

 

SKC  VC Name                    Property

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

  1   0 Adobe                          {}

  6   0 Microsoft                      {}

 

    This command pushes the current location onto a new stack named myStack and then changes to the home directory (%USERPROFILE%), which is represented in the command by the tilde symbol (~) or $home. The mystack stack now becomes the

    current stack.

 

PS D:\Users\bala>cd documents

PS D:\Users\bala\Documents> push-location $home -stackname mystack

PS D:\Users\bala>

 

pop-location

 

This cmdlet changes the current location to the location most recently pushed onto the stack. You can pop the location from the default stack or from a stack that you create by using Push-Location.You can also refer to Pop-Location by its built-in alias, "popd".

 

The parameters -stackName  specifies an alternate stack from which the location is popped out.

 

Examples :

 

The following cmdlet pushes the current location in the current stack,The current location also changes accordingly.

 

PS D:\Users\bala> pushd c:\windows

PS C:\WINDOWS>

 

Now, pushes a specific folder in the "myfolder" stack.

 

PS C:\WINDOWS> pushd d:\bala -stackname myfolder

 

PS D:\bala>

 

Now, when you issue the following 'popd' command, it changes your location to the location most recently added to the current stack.

PS D:\bala> pop-location

PS D:\Users\bala>

 

This command changes your location to the one stored in the stack "myfolder"

PS D:\Users\bala> pop-location -stackname myfolder

PS C:\WINDOWS> 

 

Now, a series of push-location and pop-location cmdlets changes the current location as below:

PS C:\WINDOWS> pushd d:\windows

PS D:\Windows> pushd hklm:\software\microsoft\powershell

PS HKLM:\software\microsoft\powershell> popd

PS D:\Windows> popd

PS C:\WINDOWS>

 

Get-Alias

 

The Get-Alias cmdlet gets the alternate names for cmdlets, functions, and executable files that have been established for the current session. This collection includes built-in aliases, aliases that you have set or imported, and aliases that you have added to your Windows PowerShell profile.

 

The -name parameter specifies the alias to retrieve. The -scope parameter is used to specify the scope in which the alias is valid:"Global", "Local", or "Script".

 

Examples :

 

This cmdlet retrieves all aliases for the current session.

 

PS D:\Users\bala> get-alias

 

CommandType     Name                                                Definition

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

Alias                   ac                                                  Add-Content

Alias                   asnp                                              Add-PSSnapin

Alias                   clc                                                 Clear-Content

Alias                   cli                                                  Clear-Item

Alias                   clp                                                 Clear-ItemProperty

Alias                   clv                                                 Clear-Variable

Alias                   cpi                                                 Copy-Item

Alias                   cpp                                                 Copy-ItemProperty

Alias                   cvpa                                                Convert-Path

Alias                   diff                                                Compare-Object

Alias                   epal                                                Export-Alias

Alias                   epcsv                                               Export-Csv

Alias                   fc                                                  Format-Custom

Alias                   fl                                                  Format-List

Alias                   foreach                                             ForEach-Object

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

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

 

This command retrieves all aliases that begin with "d".

 

PS D:\Users\bala> get-alias -name d*

 

CommandType     Name                                                Definition

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

Alias                    diff                                                Compare-Object

Alias                    del                                                 Remove-Item

Alias                    dir                                                 Get-ChildItem

 

 

The following cmdlet lists all of the aliases for the Get-Childitem cmdlet.

The name of the aliased cmdlet is stored in the Definition property of the alias. So, to find the aliases for a given cmdlet, you search for aliases with a Definition property that matches the cmdlet name.

 

PS D:\Users\bala> get-alias | where-object {$_.definition -match "get-childitem" }

 

CommandType     Name                                                Definition

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

Alias                    gci                                                 Get-ChildItem

Alias                     ls                                                  Get-ChildItem

Alias                     dir                                                 Get-ChildItem

 

 

Definition is just one property of the AliasInfo objects that Get-Alias retrieves. To find all properties and methods of AliasInfo objects, watch out for my next blog explaining "get-member" cmdlet.

 

 

 

 

 

join-path

 

The join-path cmdlet combines a path and child-path into a single path when you supply the path delimiters.

 

The parameter -path specifies the main path (or paths) to which the child-path is appended.

The parameter -childPath specifies the elements to append to the value of Path.

Wildcards are permitted in both the parameters.

 

The following command uses Join-Path to combine the "d:\Win*" path with the "System*" child path. The Windows PowerShell file system provider, FileSystem joins the path and adds the "\" delimiter.

 

 

Examples:

 

The following command combines the folder path and its sub-folder.

 

PS D:\Users\bala> join-path -path d:\win* -childpath system*

d:\win*\system*

 

You can assign the combined path to a variable and list files and folders matching the pattern.

 

PS D:\Users\bala> $mypath = join-path -path d:\win* -childpath system*

PS D:\Users\bala> get-item $mypath

 

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

 

Mode                LastWriteTime     Length        Name

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

d----        21-02-2008  22:37:14                    system

d----        13-03-2008  19:50:09                    System32

-a---        19-09-2006  03:16:04        219       system.ini

 

You may also use -resolve parameter to display the files and folders that are referenced by joining the "c:\Win*" path and the "System*" child path. It displays the same files and folders as Get-Childitem, but it displays the fully-qualified path to each item. In this command, the Path and Childpath optional parameter names are omitted.

 

PS D:\Users\bala> join-path -path d:\win* system* -resolve

 

 

D:\Windows\system

D:\Windows\System32

D:\Windows\system.ini

 

 

 

convertfrom-securestring

 

 

This cmdlet allows you to convert a secure string (System.Security.SecureString) into an encrypted standard string (System.String). Unlike a secure string, the encrypted standard string can be saved in a file for later use and can be converted back to its secure string format by using the ConvertTo-SecureString Cmdlet.

If an encryption key is explicitly specified by using the Key or SecureKey parameters, the Rijndael encryption algorithm that supports keylengths of 128, 192 or 256 bits If no key is specified, the Windows Data Protection API (DPAPI) is used to encrypt the standard string representation.

 

Examples:

 

This command enables you to create a secure string by typing at the command prompt. And then convert

the secure string stored in the $pwd variable to an encrypted standard string. The resulting encrypted

standard string is stored in the $standardpwd variable and is displayed.

 

PS D:\Users\bala> $pwd = read-host "Enter password: " -assecurestring

Enter password: : **********

PS D:\Users\bala> $pwd

System.Security.SecureString

 

 

PS D:\Users\bala> $standardpwd = convertfrom-securestring $pwd

PS D:\Users\bala> $standardpwd

01000000d08c9ddf0115d1118c7a00c04fc297eb01000000d43626bc9cc3684488e313b200404f1e 0000000002000000000003660000a8000000100

0000098038136799e65e59cb759c02ce3469a0000000004800000a000000010000000257a6430ec dd4595420c127d0f8b1a7718000000bf1efabd7c

a2759083a676f7c66a52256bc488375585028114000000855c64053daa53c62ad0f2727fc8 90a8e9511904

 

The following command is similar to the above, but it uses the encryption key specified as 16 numbers, each taking 1 byte and total 16 bytes.

 

PS D:\Users\bala> $key = (12,3,5,2,5,1,4,67,34,12,3,5,7,1,9,0)

PS D:\Users\bala> $stdpwdwithkey = convertfrom-securestring $pwd -key $key

PS D:\Users\bala> $stdpwdwithkey

c91eab0086414994cd1ad479a44ccd28271a34c1441f5e8109b29cdd23709599

 

 

 

iex

 

This is an alias for invoke-expression cmdlet and runs a Windows PowerShell expression that is provided in the form of a string.

 

 

The command parameter specifies the command and if the result is an empty array, it outputs $null and, if the result is a single-element array, it outputs that single element.

The sample command given below creates a variable named $mypros and stores the text of a command in that variable. The invoke-expression cmdlet is then used to run the command stored in the mypros variable.

 

 

Examples:

PS D:\Users\bala> $mypros = "get-process w* | sort-object Name"

PS D:\Users\bala> iex $mypros

 

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

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

 

     99       4              1256         76          26                    496      wininit

    126       3             1896         52          31                    736      winlogon

    313       9             7016       2356         82                  2052      wmpnetwk

    109       3             1640        876          33     0.11       3452     wmpnscfg

    141       3             2612        624          44     0.30         332     wuauclt

     55       3              2568        416          44     2.78       3644      wweb32

 

The command below uses iex to list all the files in current folder.

 

PS D:\Users\bala> $files = "dir"

PS D:\Users\bala> invoke-expression $files

 

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

 

Mode                LastWriteTime     Length Name

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

 

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

d-r--        13-03-2008  14:26:37            Desktop

d-r--        13-03-2008  11:30:11            Documents

d-r--        03-03-2008  12:38:44            Downloads

d-r--        13-03-2008  15:35:00            Favorites

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

d-r--        07-03-2008  23:03:33            Pictures

d-r--        23-11-2007  13:25:27            Saved Games

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

d----        13-03-2008  14:05:41            Tracing

d-r--        17-01-2008  16:50:43            Videos

-a---        04-03-2008  18:22:31        100 bb.txt

 

PS D:\Users\bala> iex $files | sort -descending

 

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

 

 

Mode                LastWriteTime     Length Name

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

d-r--        17-01-2008  16:50:43            Videos

d----        13-03-2008  14:05:41            Tracing

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

d-r--        23-11-2007  13:25:27            Saved Games

d-r--        07-03-2008  23:03:33            Pictures

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

d-r--        13-03-2008  15:35:00            Favorites

d-r--        03-03-2008  12:38:44            Downloads

d-r--        13-03-2008  11:30:11            Documents

d-r--        13-03-2008  14:26:37            Desktop

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

-a---        04-03-2008  18:22:31        100 bb.txt

 

 

Previous||Next