thraizz
thraizz

Reputation: 66

Place string before filename in PowerShell

I have the following code:

get-childitem *.log | foreach { rename-item $_ $_.Name.Replace("", "backup ") }

I want to backup .log files and need to rename them. Let's assume the look like somefile.log, I need them to be backup somefile.log. Basically I need to insert "backup" followed by one space before the filename. If I try the script above it gives me "String can't have length of 0 (zero)".

Upvotes: 0

Views: 126

Answers (1)

user189198
user189198

Reputation:

I'd recommend using .NET String formatting for this purpose, to help you build your new file name. Think of it like a template string, but you're substituting the value on the right-hand side of the -f operator for position 0 on the left-hand string.

Get-ChildItem -Path *.log | 
    ForEach-Object -Process {
        $NewName = 'backup {0}' -f $PSItem.Name
        Rename-Item -Path $PSItem -NewName $NewName
    }

The reason you're getting the exception message is because the Replace() method requires that you specify a non-zero-length string as its first parameter. In your example, you're passing in a zero-length string, hence the exception you're receiving.

IMPORTANT: The $PSItem variable is an alias to $_, and is only available on PowerShell v3.0 and later. Use $PSVersionTable to check which version of PowerShell you are currently running.

For more information about $PSItem, see this document:

Get-Help -Name about_Automatic_Variables

Upvotes: 2

Related Questions