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
|