StevenWhiting.com

A place for info I've learnt in IT & stuff. (I get a little kick back from affiliate ads & links, just so you are aware)

Browsing Posts tagged Powershell

Another one and I ended up sticking a load of notes on this for myself

Get-Item “\\SERVERNAME\files\All – all general shared files\April 2020 – Rents and service charges\Archive*.pdf” | ForEach-Object {
Rename-Item $_ ($_.Name -replace “-“, ” “) -WhatIf }

So here are my notes on the command.

Get-Item : We’re getting the contents of the folder on SERVERNAME and looking at all files ending in .pdf

We have to put the path in “” because the folder name has spaces.

We then pipe this with the pipe command (cause it looks like a pipe) | to the ForEach-Object loop. The pipe command means you pass the results of what was just to the left of it, to the next command on its right.

ForEach-Object takes each file, from the Get-Item command and with Rename-Item stores each file’s name in the Powershell global variable $_. You use that global variable because its easy, its short (typing wise) and you don’t have to declare it at the top of your script like other variables. So less code. The $_. global variable is built into Powershell.

The $_.Name takes the contents stored in Global Variable $_ and adds it to name with the (in this case) – removed from all the files that had it and replaced with a space. That is what “-” ” ” are. You’re looking for “-” in the file name and replacing with ” ” space.

The whatif is only there so the command doesn’t actually change anything, it just shows what would happen if the command ran, it can be removed once you know the script works.

Been attempting to learn Powershell, slowly. Needed help with this. Got part of it working but not fully until someone fixed it.

get-childitem -recurse | Where-Object name -Like ‘(2)‘ | ForEach-Object { remove-item -LiteralPath $_.fullname -whatif }

A shorter version

get-childitem -recurse -filter ‘*(2)*’ | remove-item -whatif

The -whatif will run the command but not execute it so NOTHING will be delete. It will just show you what it would do IF you executed the command.

I used this as my sister had loads of photos that I had to back up with

0dd123.jpg, Odd123 (2).jpg

Which was going to be an arse to go through and delete all the (2) copies.

Be aware if you are copying this script from my site because the ‘ are formatted different on the site and I believe if you paste them into Powershell it may not work. Just go and manually replace the ‘. They look exactly the same but the code behind them is somewhat different. I’ve had this happen a few times with code I’ve copied from somewhere that had ‘ in it.