as you might have seen in last testpost
I started a new blog here : The PowerShell Guy ( http://ThePowerShellGuy.com )
the Feeds you can find here :
Starting with this first entry : PowerShell : Generating RTF Help from XML help files I will no longer post on this blog.
the content on this blog will not be removed
Enjoy,
Greetings,/\/\o\/\/
Tags : PowerShell
I'm testing my new blog The PowerShell guy,
I post the same testpost here to compare
Testing codesamples for viewing and copying (do not link here, I will post this item again later after testing , in its final version with a permanent link)
I'm testing with IE7 and Bloglines, if you have problems pasting in the code on the old or new blog please leave a comment,
at the moment it looks like the The PowerShell guy
blog does not have the formatting problems I have here
Function as PowerShell code (Pre tag CodeHTMLer)
# Convert Int to Roman notation
# /\/\o\/\/ 2006
function format-Roman ($num ) {
$M = [math]::truncate($num / 1000)
$num -= $M * 1000
$D = [math]::truncate($num / 500)
$num -= $D * 500
$C = [math]::truncate($num / 100)
$num -= $C * 100
$L = [math]::truncate($num / 50)
$num -= $L * 50
$X = [math]::truncate($num / 10)
$num -= $x * 10
$V = [math]::truncate($num / 5)
$num -= $V * 5
$Roman = "M" * $M
$Roman += "D" * $D
$Roman += "C" * $C
$Roman += "L" * $L
$Roman += "X" * $X
$Roman += "V" * $V
$Roman += "I" * $num
$roman = $roman.replace('DCCCC','CM') # 900
$roman = $roman.replace('CCCC','CD') # 400
$roman = $roman.replace('LXXXX','XC') # 90
$roman = $roman.replace('XXXX','XL') # 40
$roman = $roman.replace('VIIII','IX') # 9
$roman = $roman.replace('IIII','IV') # 4
Return $Roman
}
Commandline example (Block Quote)
PoSH>format-Roman 1987
MCMLXXXVII
PoSH>format-Roman 1999
MCMXCIXPoSH>Update-TypeData C:\PowerShell\TypeData\TypedataInt32.ps1xml
PoSH>(32).toroman()
XXXII
format an Integer in Roman notation
Type extension as XML (convert whitespace, codehtmler)
* Edit * Added script again formatted by PowerShell analyzer
# Function Format-Roman
# /\/\o\/\/ 006
# http://ThePowerShellGuy.com
# HTML Formatting Generated with PowerShell Analyzer
function format-Roman ($num ) {
$M = [math]::truncate($num / 1000)
$num -= $M * 1000
$D = [math]::truncate($num / 500)
$num -= $D * 500
$C = [math]::truncate($num / 100)
$num -= $C * 100
$L = [math]::truncate($num / 50)
$num -= $L * 50
$X = [math]::truncate($num / 10)
$num -= $x * 10
$V = [math]::truncate($num / 5)
$num -= $V * 5
$Roman = "M" * $M
$Roman += "D" * $D
$Roman += "C" * $C
$Roman += "L" * $L
$Roman += "X" * $X
$Roman += "V" * $V
$Roman += "I" * $num
$roman = $roman.replace('DCCCC','CM') # 900
$roman = $roman.replace('CCCC','CD') # 400
$roman = $roman.replace('LXXXX','XC') # 90
$roman = $roman.replace('XXXX','XL') # 40
$roman = $roman.replace('VIIII','IX') # 9
$roman = $roman.replace('IIII','IV') # 4
Return $roman
}
Enjoy, Greetings /\/\o\/\/
I'm testing my new blog The PowerShell guy,
I post the same testpost here to compare
Testing codesamples for viewing and copying (do not link here, I will post this item again later after testing , in its final version with a permanent link)
I'm testing with IE7 and Bloglines, if you have problems pasting in the code on the old or new blog please leave a comment,
at the moment it looks like the The PowerShell guy
blog does not have the formatting problems I have here
Function as PowerShell code (Pre tag CodeHTMLer)
# Convert Int to Roman notation
# /\/\o\/\/ 2006
function format-Roman ($num ) {
$M = [math]::truncate($num / 1000)
$num -= $M * 1000
$D = [math]::truncate($num / 500)
$num -= $D * 500
$C = [math]::truncate($num / 100)
$num -= $C * 100
$L = [math]::truncate($num / 50)
$num -= $L * 50
$X = [math]::truncate($num / 10)
$num -= $x * 10
$V = [math]::truncate($num / 5)
$num -= $V * 5
$Roman = "M" * $M
$Roman += "D" * $D
$Roman += "C" * $C
$Roman += "L" * $L
$Roman += "X" * $X
$Roman += "V" * $V
$Roman += "I" * $num
$roman = $roman.replace('DCCCC','CM') # 900
$roman = $roman.replace('CCCC','CD') # 400
$roman = $roman.replace('LXXXX','XC') # 90
$roman = $roman.replace('XXXX','XL') # 40
$roman = $roman.replace('VIIII','IX') # 9
$roman = $roman.replace('IIII','IV') # 4
Return $Roman
}
Commandline example (Block Quote)
PoSH>format-Roman 1987
MCMLXXXVII
PoSH>format-Roman 1999
MCMXCIXPoSH>Update-TypeData C:\PowerShell\TypeData\TypedataInt32.ps1xml
PoSH>(32).toroman()
XXXII
format an Integer in Roman notation
Type extension as XML (convert whitespace, codehtmler)
* Edit * Added script again formatted by PowerShell analyzer
# Function Format-Roman
# /\/\o\/\/ 006
# http://ThePowerShellGuy.com
# HTML Formatting Generated with PowerShell Analyzer
function format-Roman ($num ) {
$M = [math]::truncate($num / 1000)
$num -= $M * 1000
$D = [math]::truncate($num / 500)
$num -= $D * 500
$C = [math]::truncate($num / 100)
$num -= $C * 100
$L = [math]::truncate($num / 50)
$num -= $L * 50
$X = [math]::truncate($num / 10)
$num -= $x * 10
$V = [math]::truncate($num / 5)
$num -= $V * 5
$Roman = "M" * $M
$Roman += "D" * $D
$Roman += "C" * $C
$Roman += "L" * $L
$Roman += "X" * $X
$Roman += "V" * $V
$Roman += "I" * $num
$roman = $roman.replace('DCCCC','CM') # 900
$roman = $roman.replace('CCCC','CD') # 400
$roman = $roman.replace('LXXXX','XC') # 90
$roman = $roman.replace('XXXX','XL') # 40
$roman = $roman.replace('VIIII','IX') # 9
$roman = $roman.replace('IIII','IV') # 4
Return $roman
}
Enjoy, Greetings /\/\o\/\/
On CodePlex there is released a major update to PSCX (PowerShell Community Extensions) that I think folks will find very useful.
be sure to Check it out !!
PowerShell Community Extensions is a PowerShell Snapin that provides a
number of widely useful cmdlets. PSCX is not affliated with Microsoft
or the Windows PowerShell team at Microsoft. We are a few (at the moment)
passionate PowerShell users who wanted more cmdlets than Micorsoft was
able to deliver in v1.0. So we have taken it upon ourselves to create
some of those cmdlets and make them available to the community.
You can download it from:
http://www.codeplex.com/PowerShellCX/Release/ProjectReleases.aspx
If you run into problems please report them here:
http://www.codeplex.com/PowerShellCX/WorkItem/List.aspx
The readme and about_pscx help topic you can find on the download page also, for you to check out what
is new in version 1.0.
Enjoy!
--
The PSCX crew (Keith Hill, Alex Angelopoulos, Mabster, DBMsW, and MoW)
P.S. If you are passionate about PoSh and can contribute by writing C#
cmdlets, let us know. We're looking for more help.
Greetings,/\/\o\/\/
Tags : PowerShell
Jeffery Hicks did a 2 part series on his blog about accessing evenlogs in PowerShell
PowerShell Event Log Filtering ,
in the second part he did use WMI to acces remote eventlogs, I posted an example in the comments using .NET for it.
PoSH>$logs = [System.Diagnostics.EventLog]::GetEventLogs('Server')
PoSH>$logs[0]
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
20,480 7 OverwriteOlder 829 Application
PoSH>$logs[0].machinename
Server
PoSH>$logs[0].entries | where `
>> {($_.EntryType -eq "Warning" -OR $_.EntryType -eq "Error") `
>> -AND ($_.TimeWritten -ge $recent)}
As an reaction to Remote Event Log Filtering in my comment Here where I did the example in the first part PowerShell Event Log Filtering again but then using the .NET object directly, he posted about powershell users not (yet) knowing the .net objects :
but a good thing about this they allready did learn about then using the CMDlet get-eventlog, as this is merely a wrapper for the .NET objects, as the examples below will show, the output and objects will be the same, only in this case you can use it agains remote computers, also you as you can see in the last example you can even "Switch" to a remote computer using only the PowerShell get-EventLog -list command, so you can see that you actualy did allready learn how to use it in the first part of Jeffery Hicks 's series only you might not know it yet ;-).
Get-EventLog -list is actualy the same as System.Diagnostics.EventLog]::GetEventLogs() :
PoSH>Get-EventLog -list
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
20,480 7 OverwriteOlder 829 Application
...PoSH>[System.Diagnostics.EventLog]::GetEventLogs()
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
20,480 7 OverwriteOlder 829 Application...
As you can find out like this
[System.Diagnostics.EventLog] | gm -s | fl *
in the output from that you will find that the latter method takes also a machinename parameter :
...
TypeName : System.Diagnostics.EventLog
Name : GetEventLogs
MemberType : Method
Definition : static System.Diagnostics.EventLog[] GetEventLogs(), static System.Diagnostics.EventLog[] GetEventLogs(Str
ing machineName)...
Also $al = get-eventlog Application is almost the same as $al = new-object System.Diagnostics.EventLog('Application')
only here you can see that here also the result is alsmost the same, only the latter method it not completely the same, as get-eventlog CMDlets allready calls the entries() method
PoSH>$al = get-eventlog Application
PoSH>$alIndex Time Type Source EventID Message
----- ---- ---- ------ ------- -------PoSH>$al = new-object System.Diagnostics.EventLog('Application')
PoSH>$al
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
20,480 7 OverwriteOlder 829 ApplicationPoSH>$al.Entries
Index Time Type Source EventID Message
----- ---- ---- ------ ------- -------# Remote
PoSH>new-object System.Diagnostics.EventLog('Application','foo')
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
As again this method has more overloads :
PoSH>[System.Diagnostics.EventLog].GetConstructors() |% {"$_"}
Void .ctor()
Void .ctor(System.String)
Void .ctor(System.String, System.String)
Void .ctor(System.String, System.String, System.String)
in this case (no Enums all strings ) that is not that helpfull but we have help here, same as in the example in yesterdays post about the VbScript to PowerShell converting guide online, me (and Others) did this before for MSDN
PoSH>Function Get-MSDN ($type = "default") {
>> (new-object -com shell.application).Open("http://msdn2.microsoft.com/library/$type.aspx")
>> }
>>
PoSH>Get-MSDN System.Diagnostics.EventLog
So again after connecting using the .NET object for the rest it is also the same and you can still use the eventlog methods as with the indexing into the getEventlogs() method in the first example $logs[0] this can even be handy
PoSH>$al = new-object System.Diagnostics.EventLog('Application')
PoSH>$al | Get-Member -membertype MethodTypeName: System.Diagnostics.EventLog
Name MemberType Definition
---- ---------- ----------
PoSH>$al.WriteEvent
MemberType : Method
OverloadDefinitions : {System.Void WriteEvent(EventInstance instance, Params Object[] values), System.Void WriteEvent(E
ventInstance instance, Byte[] data, Params Object[] values)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Void WriteEvent(EventInstance instance, Params Object[] values), System.Void WriteEvent(Ev
entInstance instance, Byte[] data, Params Object[] values)
Name : WriteEvent
IsInstance : True
Even a more nice example for this is the following example we use the get-eventlog -list command to get the eventlogs and then switch to another machine by changeing the machinename property as that is get / set
So it is not even needed to use the .NET Object to work agains remote computers :
PoSH>$logs = Get-EventLog -list
PoSH>$logs[0]Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
20,480 7 OverwriteOlder 829 ApplicationPoSH>$logs[0].machinename = "foo"
PoSH>$logs[0]Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
Application
So while you use get-member and use the Cmdlets in the background you also learn to know the .NET object,
so this is a good glidepath to using the .net classes when you are in need for the extra power they can give you (e.g. remoting, other functionality and /or Speed), I hope this post will also help by showing it is not that different from using the CMDlets as you get back the same .NET objects.
I think this is a good middle way ;-)
Enjoy,
Greetings,/\/\o\/\/
Tags : PowerShell
as you can read here PowerShell Scripting Contest - 2 weeks left, here Don't miss the Microsoft PowerShell Contest, here PowerShell Scripting Contest, herePowerShell Scripting Contest and here PowerShell Scripting Contest - 2 weeks left , there is still some time left te enter in the
Windows PowerShell Scripting Sweepstakes!
November 1 – December 15, 2006
What also can help is the excelent:
VbScript to Windows PowerShell translation guide
for looking up VbScript commands, or inspiration, for example yo could write a function to do a quick lookup in it
for example you can write a function to do that from the PowerShell console so yo cando :
PoSH>convert-VbScript
PoSH>convert-VbScript inputbox
PoSH>convert-VbScript getObject
to start internet explorer to do a quick lookup in that guide to get help on how to translate the VbScript command you remember to PowerShell, that could be as simple as this :
Started without the commandname it starts the index otherwise it will bring you directly to the page about the command given
or one to remind how much time long you still have
PoSH>function get-TimeLeftToEnterPowerShellContest {(get-date -date "12/15/2006 23:55").Subtract((get-date))}
PoSH>get-TimeLeftToEnterPowerShellContestDays : 11
Hours : 2
Minutes : 21
Seconds : 43
Milliseconds : 719
Ticks : 9589037192755
TotalDays : 11.0984226767998
TotalHours : 266.362144243194
TotalMinutes : 15981.7286545917
TotalSeconds : 958903.7192755
TotalMilliseconds : 958903719.2755
hope this guide and the examples get you started with an script for the contest,
Enjoy,
Greetings,
/\/\o\/\/
Tags : PowerShell
In PowerShell you often see the use of enum's
for some info , examples of Enums and there usage see :
/\/\o\/\/ PowerShelled: Get SpecialFolder Locations in Monad,
/\/\o\/\/ PowerShelled: Adding a Simple AccesRule to a file ACL in MSH
as you can see in the Special Forder function this is very handy for some parameters :
It is not possible yet to create Enums and classes directly in PowerShell, but there is a way by using Reflection :
# Make a Custom Enum in PowerShell
$cd = [AppDomain]::CurrentDomain
$an = new-object System.Reflection.AssemblyName('Mow')
$ab = $cd.DefineDynamicAssembly($an,'RunAndSave')
$mb = $ab.DefineDynamicModule($an.Name, "$($an.Name).dll")
$eb = $mb.DefineEnum("Fruit",'Public', [int])
& {
$eb.DefineLiteral('Apple',1)
$eb.DefineLiteral('strawberry',2)
$eb.DefineLiteral('Banana',3)
} | out-null
$t = $eb.CreateType()
It might not look that way, but this is "Fasten your Seatbells (c) Jeffrey Snover" - Code (you can even create complete classes this way but that's outside my "Scope" (@ reading developers : but this would be real cool material for a CMDlet *Wink* *Wink* )),
Hence, I won't go into the workings to much, to get an impression after runnin the code try :
$cd,$an,$mb,$eb | gm
but the code as is, is easy to customize, e.g. to add a Kiwi to the list with number 4 add a line like this
$eb.DefineLiteral('Kiwi',4)
...
PoSH>$t = $eb.CreateType()
PoSH>[fruit]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Fruit System.EnumPoSH>[enum]::GetNames([fruit])
Apple
strawberry
BananaPoSH>function new-FruitShake ([fruit]$f) {"Here is your $f Shake"}
PoSH>new-FruitShake Apple
Here is your Apple ShakePoSH>new-FruitShake chocolate
new-FruitShake : Cannot convert value "chocolate" to type "Fruit" due to invalid enumeration values. Specify one of the
following enumeration values and try again. The possible enumeration values are "Apple, strawberry, Banana".
At line:1 char:15
+ new-FruitShake <<<< chocolate
If you have my custom tabcompletion
you can even tabcomplete on it :
[fruit]A[tab]
[fruit]Apple
Enjoy,
Greetings /\/\o\/\/
Tags : PowerShell
For the PowerShell calendar :
TechNet Webcast: An Overview of Windows PowerShell (Level 200)
Presenter: Don Jones, Scripting Guru, Author, SAPIEN Technology
Event Name: TechNet Webcast: An Overview of Windows PowerShell (Level 200)
Start Date: 12/19/2006
Start Time: 1:00 PM (GMT-08:00) Pacific Time (US & Canada)
End Date: 12/19/2006
End Time: 2:00 PM (GMT-08:00) Pacific Time (US & Canada)
Enjoy,
Greetings,
/\/\o\/\/
Tags : PowerShell
One question/remark I did hear very often at the IT Forum is about available books for PowerShell and about Editors for PowerShell .
Don Jones, from Sapiens, well know from the script Editor PrimalScript . (PrimalScript 4.1 introduces support for Microsoft's Windows PowerShell! and did go RTM at the same time as PowerShell, at the IT Forum.!!)
But they do much more, as giving Scripting Training (also PowerShell) and Publishing (SAPIEN Press)
Also they cover a lot of PowerShell material online : - A blog http://sapien.eponym.com/blog, - Scripting / PowerShell Forums :ScriptingAnswers.com and a search engine with PowerShell support: SearchScripting.com
Today Don Jones also did announce that the book he was writing Windows PowerShell: TFM has gone Gold,
See the following message I got from him :
Jeff Hicks and I are very pleased to announce that Windows PowerShell: TFM is now “gold,” meaning the manuscript is complete and should be off to the printer’s sometime this week. We’re just waiting on the cover design to be completed. The manuscript checked in at 470 pages, including the index, meeting our target for a highly on-topic book that administrators will find approachable and comfortable to read.
Pre-orders are available on Amazon.com, and our first official sample chapters are posted, along with a complete table of contents (all in one PDF) on www.SAPIENPress.com/powershell.asp. The book’s sample scripts are also available now as a free download for one and all, whether they’ve purchased the book or not.
We hope to announce shipping and general availability dates in December.
Some quick facts:
- Almost 500 pages of Windows PowerShell-flavored goodness
- Walks a Windows admin through the PoSH learning process from the ground up
- Focuses on task completion, helping admins get the job done faster
- Chosen by more than 50% of Amazon.com customers shopping for a PoSH title
- Currently in the top 100,000 books on Amazon.com
- Book is supported personally by the authors through a forum on www.ScriptingAnswers.com.
I did not read the book yet,only the preview chapter I did post about before, but when I do, I will do another post about my impression of the book but I'm very sure it will be a great read and this will be another "Must have" Book about PowerShell, from the sample chapters, seeing all the PowerShell coverage and support they provide online, and of course the writer Don Jones,who did write very good scripting books before.
I had the pleasure to meet Don Jones 2 times, at TechEd Boston and on the IT forum, on both events he also did give some impressive Demos of the PowerShell support in PrimalScript.He is a great guy, a real Scripting and PowerShell Guru, a good presenter and very good in explaining and teaching.
Hence, I'm sure I can recommend this book for learning PowerShell.
I also got the opportunity to, and did review the book from Bruce Payette that is available in the :Windows PowerShell in Action - EARLY ACCESS EDITION program, I finished reading it in my vacation, and I really loved this book, it is well written, good examples, and lots of inside and background information, the book does focus on the language itself and how PowerShell is structured and why ,starting at the core, as there are some advanced concepts that lay at the base of how PowerShell works,.
The PowerShell in Action book is a "must Read" , I think it is a great book, one of the best technical books I did read ever , More in a later post
the RTM book is a different format and from another viewpoint, so it could be good combination, a more in a later post when I also did read TFM.
So next to the excellent documentation (getting started and UserGuide) that does come with the PowerShell installation (if you did not do that yet, be sure to check it out !, it is really great !!! )
There are, next to the books about Monad and MSH beta s :
Monad (PowerShell Beta) see :/\/\o\/\/ PowerShelled: Series about Monad on Computerworld ,
and Lee holmes (who is Member of the PowerShell team and also has a great powerShell blog ) wrote O'Reilly PowerShell Quick Reference (see also his Blog O'Reilly PowerShell Quick Reference Now Available )
and also we have the Free E-book Don Jones did before See /\/\o\/\/ PowerShelled: Powershell links and free E-book :
Now allreay two very books, to learn more about PowerShell (release), that you can get your hands on, and there are much more in the pipeline ,amongs others : Professional Windows from Andrew Watt ,
Andrew Watt is a MVP and also is very active on the Newsgroup : microsoft.public.windows.powershell NewsGroup and also has a PowerShell blog : PowerShell Ponderings
Enjoy,
Greetings,
/\/\o\/\/
Tags : PowerShell
On the NewsGroup microsoft.public.windows.powershell ,
there was a Question about : Advanced renaming directly in Powershell?
The Question was about doing advanced file renaming, to rename a set of files like this :
file.ex2
file.ext
file_1.ex2
file_1.ext
file_2.ext
to the following format, Giving a base number and then rename the files and use the _3 as an offset to the number
file12.ex2
file12.ext
file13.ex2
file13.ext
file14.ext
Now the rename-object commandlet in PowerShell is very powerfull for this, some basic renaming might be a bit hard at first see also /\/\o\/\/ PowerShelled: PowerShell : How Can I Rename Files Using ... (a CSV file) and commments on this post Upgrading MSH, My first Windows PowerShell Commands about renaming *.msh to *.ps1,
But as the -NewName parameter takes a ScriptBlock as a parameter it is very handy to use some more advanced logic to rename file as you also can use the Power of the -Match and -Replce Operators RegEx support.
I Came up with this oneliner for this task :
PoSH>$num = 12
PoSH>ls file*.ex* | rename-item -newname {if($_.name -match '_(\d)'){$num = $num + $matches[1]};$_.name -replace "file.*\.", "file$num."} -WhatIfWhat if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ex2 Destination: C:\PowerShell\file12.ex2".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ext Destination: C:\PowerShell\file12.ext".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ex2 Destination: C:\PowerShell\file13.ex2".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ext Destination: C:\PowerShell\file13.ext".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_2.ext Destination: C:\PowerShell\file14.ext".
As there is happening a lot in this one line of code I'm going to work it out a bit more in this post.
lets first make the files and list them :
PoSH>sc file.ext 'a'
PoSH>sc file.ex2 'a'
PoSH>sc file_1.ex2 'a'
PoSH>sc file_1.ext 'a'
PoSH>sc file_2.ext 'a'PoSH>ls file*.ex*
Directory: Microsoft.PowerShell.Core\FileSystem::C:\PowerShell
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 11/25/2006 1:55 PM 3 file.ex2
-a--- 11/25/2006 1:54 PM 3 file.ext
-a--- 11/25/2006 1:55 PM 3 file_1.ex2
-a--- 11/25/2006 1:55 PM 3 file_1.ext
-a--- 11/25/2006 2:15 PM 3 file_2.ext
Now that we have listed the files we want to act upon ( al files starting with file and ending with .ex* )
we can pipe them to rename object :
PoSH>ls file*.ex* | rename-item -newname {$_.name} -WhatIf
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ex2 Destination: C:\PowerShell\file.ex2".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ext Destination: C:\PowerShell\file.ext".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ex2 Destination: C:\PowerShell\file_1.ex2".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ext Destination: C:\PowerShell\file_1.ext".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_2.ext Destination: C:\PowerShell\file_2.ext".
Note that in the scriptblock I provided to the -newname parameter I have access to the complete File Object in the $_ variable, I just use it to get the name property and do not do any processing yet, also note that I added the -WhatIf parameter so no changes are made and I we can test freely till we got it right without messing up your testfiles.
Now lets start by adding the Base Number for it, in this case 12 that I put in the variable $num
PoSH>$num = 12
PoSH>ls file*.ex* | rename-item -newname {$_.name -replace "file.*\.", "file$num." } -WhatIfWhat if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ex2 Destination: C:\PowerShell\file12.ex2".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ext Destination: C:\PowerShell\file12.ext".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ex2 Destination: C:\PowerShell\file12.ex2".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ext Destination: C:\PowerShell\file12.ext".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_2.ext Destination: C:\PowerShell\file12.ext".
In this first step we use the -replace operator to insert the basenumber given into the filename by replacing everything between the word file and the extension.
note that -replace uses RegEx expressions not wildcards so the expression looks like this : "file.*\." first the word file, then we need to use a dot . before the * that means any character and we need to escape the last (literal) dot by escaping it \.
but as you can see in the following steps this makes it much more powerfull as also the -mach operator uses the regular expression engine, so we can use the full RegEx power.
Next we need to raise the number for filesnames that do contain an _ with the number that is behind it.
we can use the mach operator to do this (note again that we use -WhatIf so are free just to return anything we want) :
PoSH>ls file*.ex* | rename-item -newname {$_.name -match '_' } -WhatIf
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ex2 Destination: C:\PowerShell\False".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file.ext Destination: C:\PowerShell\False".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ex2 Destination: C:\PowerShell\True".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_1.ext Destination: C:\PowerShell\True".
What if: Performing operation "Rename File" on Target "Item: C:\PowerShell\file_2.ext Destination: C:\PowerShell\True".
The -Mach operator returns $True or $False , but does more it also fills the $maches variable, lets look at this with a single filename to look how this works :
PoSH>"file_1.ex2" -match '_'
TruePoSH>$matches
Name Value
---- -----
0 _PoSH>"file_1.ex2" -match '_\d'
TruePoSH>$matches[0]
_1
You can see here that the $matches variable does contain the Capture found, in the second example I did add \d that means any digit.
but as with a fullBlown [regex] object also the -match operator supports subCaptures, so we can get the Number :
PoSH>$matches
Name Value
---- -----
1 1
0 _1PoSH>$matches[1]
1
So now we can combine the $true returned by -match and the capture made in $matches with an If statement to do the Math :
PoSH>if ("file_1.ex2" -match '_(\d)'){$matches[1]}
1
PoSH>if ("file_2.ex2" -match '_(\d)'){$matches[1]}
2
PoSH>if ("file_2.ex2" -match '_(\d)'){$num + $matches[1]}
14
and all can be combined the the one-liner I did post on the NewGroup, what also could be written like this in PowerShell to make it a bit more readable and you can still just past it into the PowerShell console
$num = 12
Dir file*.ex* |
rename-item -newname {
if($_.name -match '_(\d)'){
$num = $num + $matches[1]
}
$_.name -replace "file.*\.", "file$num."
} -WhatIf
I hope this post makes it clear how easy it is to make and test advanced rename jobs interactivly on the console by using -WhatIf and command history, and then while ready format as a script, and how powerfull the RegEx support of -match and -Replace is.
Enjoy,
Greetings,
/\/\o\/\/
Tags : PowerShell
October 2005 November 2005 December 2005 January 2006 February 2006 March 2006 April 2006 May 2006 June 2006 July 2006 August 2006 September 2006 October 2006 November 2006 December 2006