Powershell: How to rename all files in a folder

Powershell Header

Sometimes you need a fast way to rename a lot of file. With Powershell this is pretty easy. You list all files in the directory and you can use this object with a foreach loop.

This script basically changes the extension from .JPEG to .jpg:

$files = Get-Content
foreach ($file in $files) {
	$newFileName=$file.name.replace(".JPEG",".jpg")
	Rename-Item $file $newFileName
}

Powershell: Parsing XML part 1

Powershell Header

In my company we started to use XML files as configuration files. So we use it for some configurations of servers or automation for our robots. In Powershell there is a pretty easy way for parsing XML. In Powershell there is an object type for XML, so you just can use the get-content Cmdlet to read the XML file into the object.


$xmldata = get-content "C:\XMLFiles\mydata.xml"

When you create a function for reading XML files you also can set the XML object to global.


$global:xmldata = get-content "C:\XMLFiles\mydata.xml

Now $xmldata is a object which includes all the data of the mydata.xml.

Lets view the content of the mydata.xml file. We need this to understand the following commands.

<TodoList ID = “Week21″>

<Task action=”create” ID=”1″>
<Name>Peter</Name>
<Dept>Administration</Dept>
<email>peter@contoso.com</email>
</Task>

<Task action=”create” ID=”2″>
<Name>Thomas</Name>
<Dept>Administration</Dept>
<email>thomas@contoso.com</email>
</Task>

<Task action=”delete” ID=”3″>
<Name>Steve</Name>
<Dept>IT</Dept>
<email>steve@contoso.com</email>
</Task>

</TodoList>

Now we wanna get all unique Accounts listed

$xmldata.TodoList.Task | %{$_.Name} | select-object -unique

Peter
Thomas
Stefan

We can also create a new object for a specific Task

[Object]$xmltask2 = $xmldata.TodoList.Task | Where-Object {$_.ID -eq "2"}

Now we have a new object with data from Task ID 2. If we wanna see the name from this we just use the same command with the new object

$xmltask3 | %{$_.Name}

Thomas

We can do a lot more with this, but I will bring this up in the next blog posts.