BimberX
BimberX

Reputation: 33

rename a file if another file exists in Powershell

I have been looking for the way to do this using get-children and rename combined with if but no luck.

I want to search all subdirectories (subdir1, subdir2, etc) of a directory (test) for a file "trigger.txt" and if the file exists in one of these subdirectories I want to change the name of another file in the same subdirectory (changeme.txt to _changeme.txt)

Rephrasing:

If file subdir1\"trigger.txt" exists change subdir1\"changename.txt" to subdir1\"_changename.txt"

I have found scripts to change the name of file if it exists and to look for a file but I cannot connect it together... Any help?

Upvotes: 2

Views: 4498

Answers (2)

Keith Hill
Keith Hill

Reputation: 201622

Try this:

Get-ChildItem -r trigger.txt | Foreach {Rename-Item (Join-Path $_.DirectoryName changeme.txt)  _changeme.txt}

And if you want the terse version:

ls -r trigger.txt | %{rni (join-path $_.DirectoryName changeme.txt) _changeme.txt}

Upvotes: 2

mikekol
mikekol

Reputation: 1862

Perhaps something like this?

ls -filter trigger.txt -recurse | %{
    $original = Join-Path $(Split-Path $_.FullName -Parent) "ChangeMe.txt"
    $newName  = Join-Path $(Split-Path $_.FullName -Parent) "_ChangeMe.txt"

    if ([IO.File]::Exists($original)) {
        Write-Host "Renaming $($original)..."
        ren -Path $original -NewName $newName
    }
}

Upvotes: 0

Related Questions