2

I'm trying to bulk rename a bunch of files with PowerShell, however, I run into an error which I don't know what to do with and searching for it didn't give me any solutions either.

Error message:

Rename-Item : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'NewName'.


For example: 2068227794 (0x8f860be3).bnk to 0x8f860be3_0001.bnk

In this particular case $hex_name is 0x8f860be3.

$source = "K:\_test"

Get-ChildItem -Path $source -File -Recurse -Include "* (0x*).*" | ForEach-Object {

   $prefix, $hex_name = ($_.BaseName).Split('()')
   Rename-Item -Path $_ -NewName ($hex_name + "_0001" + $_.Extension)

}
10
  • 2
    That split would return three elements so $hex_Name would be an array with two elements.
    – EBGreen
    Commented Mar 22, 2018 at 16:29
  • What is an example file name and what would you expect the new name to be? Data examples and expectations are important for asking good questions.
    – EBGreen
    Commented Mar 22, 2018 at 16:30
  • 1
    try referencing $hex_name[0] to get the 0x8f860be3 without the parens, or change your split to something like $firstParen, $hex_name, $secondParenAndExt = ($_.BaseName).Split('()') Commented Mar 22, 2018 at 16:39
  • 3
    $hex_name = ($_.BaseName).Split('()')[1]
    – EBGreen
    Commented Mar 22, 2018 at 16:45
  • I suppose you've already tried something like ($hex_name + "_0001" + $_.Extension).ToString() and confirmed that does not work. docs.microsoft.com/en-us/dotnet/api/…. Even if you need to set as a variable within the loop and then use with the Rename-Item.... just a quick idea with no testing. Commented Mar 22, 2018 at 16:48

1 Answer 1

2

As this question was answered in the comments, I'll answer my own question so it is marked as solved.

The error occurs as $hex_name is an array which contains the hex string and the rest. There are 2 simple solutions:

Selecting the item directly:

$hex_name = ($_.BaseName).Split('()')[1]

Assigning the unwanted rest to a new variable:

$prefix, $hex_name, $rest = ($_.BaseName).Split('()')

All credit goes to EBGreen.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .