2

I have been working to rename all files within a folder that are older than 5 days within PowerShell.

The file names all read as:

XTYPE  -to-  CoOrd & WBS - 20140313
XTYPE  -to-  CoOrd & WBS - 20140314

etc. Occasionally there will be some slight anomalies such as:

XTYPE  -to-  CoOrd & WBS - 20140316 - do not use
XTYPE  -to-  CoOrd & WBS - 20140314 (AutoSaved)

Now I want simply to remove the " & WBS " from each of the files (all saved in excel format so the files would be)

XTYPE  -to-  CoOrd- 20140313
XTYPE  -to-  CoOrd- 20140314
XTYPE  -to-  CoOrd- 20140316 - do not use
XTYPE  -to-  CoOrd- 20140314 (AutoSaved)

Now my code so far I believe is near enough there...

$myFolder = '\\iiGlasgow.co.uk\public\Controls\Archived Files\'
ForEach ($File in Get-Childitem $myFolder | Where-Object { $_.LastWriteTime   -lt (get-date).AddDays(-5)})

So I have set the folder and advised PowerShell to only deal with items over 5 days old.

I cannot get it to replace the partial string elements however... Its probably really simple I just can't see it. I've scoured the internet and tried all sorts of iterations but it is not happening.

So my final elements which I believe to be the closest to a solution then read...

{
$myFile = $file.name
$myFullFilename = $file.FullName
$myRenamed = $myFile.Replace(" & WBS ","") 
}

The script in its entirety for ease?

$myFolder = '\\iiGlasgow.co.uk\public\Controls\Archived Files\'
ForEach ($File in Get-Childitem $myFolder | Where-Object { $_.LastWriteTime   -lt (get-date).AddDays(-5)})
{
$myFile = $file.name
$myFullFilename = $file.FullName
$myRenamed = $myFile.Replace(" & WBS ","") 
}

Your help and pointers at my mistakes are as ever massively appreciated!

1 Answer 1

2

I would extend the Where-Object cmdlet and filter all basenames containing & WBS. Then just rename the file using the Rename-item cmdlet:

$myFolder = '\\iiGlasgow.co.uk\public\Controls\Archived Files\'
Get-Childitem $myFolder | 
    Where-Object { $_.LastWriteTime -lt (get-date).AddDays(-5) -and $_.BaseName -Match ' & WBS ' } | 
    Foreach {
        $_ | Rename-Item -NewName ($_.Name -replace ' & WBS ')
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.