Cannot Bind Argument to Parameter 'NewName' because it is an empty string - powershell

Get-ChildItem -Name *.txt | Rename-Item -NewName { $_.name -replace '\.txt','.log' }
I have 3 text files in my current path, I'm using this snip bit of code found in the last example of...
get-help rename-item -full
(Powershell Version 2.0). For whatever reason, I keep receiving the following error:
Rename-Item : Cannot bind argument to parameter 'NewName' because it is an empty string.
At line:1 char:40
+ Get-ChildItem -Name *.txt | Rename-Item <<<< -NewName { $_.name -replace
'\.txt','.log' }
+ CategoryInfo : InvalidData: (testfile3.txt:PSObject) [Rename-Item],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Rena
meItemCommand
Clearly my alteration form .txt to .log isn't an empty string, and this matches exactly the same code as in found in Microsoft's last example of the cmdlet rename-item.

Either don't use the -Name parameter since that outputs just strings containing the full path or don't reference the Name property:
Get-ChildItem -Name *.txt | Rename-Item -NewName { $_ -replace '\.txt','.log' }

Related

is there any way to move files at once different locatios in powershell

tried this
Get-ChildItem -Path P:\Users\SMarri\Desktop\testingPS -Recurse |? {($_.LastWriteTime -lt (Get-Date).AddDays(-1))} | move-item -destination "P:\Users\SMarri\Desktop\testing" ,"P:\Users\SMarri\Desktop\C"
Getting below error
Move-Item : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Destination'. Specified method is not supported.
At line:1 char:140
+ ... destination "P:\Users\SMarri\Desktop\testing" ,"P:\Users\SMarri\Deskt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Move-Item], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.MoveItemCommand
You can chain multiple Move-Item/Copy-Item commands by using the -PassThru parameter switch:
Get-ChildItem -Path P:\Users\SMarri\Desktop\testingPS -Recurse |Where-Object {
$_.LastWriteTime -lt (Get-Date).AddDays(-1)
} |Move-item -Destination "P:\Users\SMarri\Desktop\testing" -PassThru |Copy-Item -Destination "P:\Users\SMarri\Desktop\C"
-PassThru causes Move-Item to output the file after the move operation, making it available for Copy-Item to copy.

Renaming all text files in a directory

I altered some code for powershell:
Get-ChildItem -Filter *.txt | ForEach-Object { # Loop over files of interest
$newName = (Get-Content $_.FullName -Head 1)[-1] # Extract 1st line
$_ | Rename-Item -NewName $newName # Rename input file
}
It is supposed to take each text file in a directory, and rename it to the first line of the file.
Rename-Item : The path is not of a legal form.
At line:3 char:8
+ $_ | Rename-Item -NewName $newName # Rename input file
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Rename-Item], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.RenameItemCommand
But it gives me that error.
Use (Get-Content $_.FullName -First 1) instead of (Get-Content $_.FullName -Head 1)[-1]
-First has been introduced in PowerShell 3.0.

How do I remove a leading or trailing blank space in file name with PowerShell?

I'm basically trying to trim() any filenames that have a leading or trailing space at the end of the name. This is the code I've got so far
$foldersToCheck = "$env:userprofile\documents", "$env:userprofile\pictures", "$env:userprofile\desktop"
foreach ($folder in $foldersToCheck) {
get-childitem -path $folder -recurse | foreach-object {
if ($_.name.startswith(" ") -or $_.name.endswith(" ")) {
$newName = $_.name.trim()
rename-item -path $_ -newName $newname
}
}
}
If I create a test file (c:\users\someusername\desktop\ test.txt), then I receive this error
rename-item : Cannot rename because item at ' test.txt' does not exist.
At line:6 char:13
+ rename-item -path $_ -newName $newname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
So, it looks like it found the file that needs to be renamed, but then says it doesnt exist.
The problem here is that PowerShell resolves $_ to just the file name when attempting to convert it to a string it can bind to -Path.
Explicitly pass the full path of the file and it'll work:
Rename-Item -Path $_.FullName -NewName $newname
Alternatively, pipe the $_ file object to Rename-Item and PowerShell will automatically figure out that it needs to bind $_.FullName to Rename-Item's -LiteralPath parameter:
$_ |Rename-Item -NewName $newname
You can also turn the whole loop into a single pipeline, and then take advantage of a pipeline-bound expression against -NewName:
$foldersToCheck |Get-ChildItem -Recurse |Rename-Item -NewName { $_.Name.Trim() }
If the existing Name and the -NewName values are the same, Rename-Item will just leave the files alone anyway :)

PowerShell complaining about path, But path is valid

In the following code, when $client = XRS1
if (Test-Path C:\dbbackups\cm_$client-*.full.bak){
Rename-Item -path C:\dbbackups\cm_$client-*.bak -newname cm_$client.bak
Write-Host "New file found, renamed to: cm_$client.bak"
The Test-Path statement can find C:\dbbackups\cm_xrs1-2013414.full.full.bak but -path in the Rename-Item can't.
The error I get is
Rename-Item : Cannot process argument because the value of argument "path" is not valid. Change the value of the "path" argument and run the operation again.
At C:\Users\Aaron\Documents\0000 - PowerShell DB Update Utility\UpdateCMDatabases.ps1:167 char:1
+ Rename-Item -path C:\dbbackups\cm_$client-*.bak -newname cm_$client.bak
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Rename-Item], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand
For those who need only a one line command, please note that this is a powershell only error and that this command works just fine in the good old command prompt.
The full form of the powershell command is
ren -Path [something with a wildcard] -NewName [something else]
The error relates to the value of the Path parameter. It accepts wildcards in the path but it must resolve to a single file [1]. To use wildcards with powershell, you'll need to pipe them one by one to the rename item command. Here is an example to rename txt files to log [2]:
get-childItem *.txt | rename-item -newname { $_.name -replace '\.txt','.log' }
If Rename-Item does not like a wildcard, then do not give it one
Convert-Path C:\dbbackups\cm_$client-*.full.bak | % {
if (Test-Path $_) {
Rename-Item $_ cm_$client.bak
}
}

replace names of all directiories and files in PS

I want to replace all space characters into "_" in names of all subfolders and files.
Unfortunately when I type:
Get-ChildItem -recurse -name | ForEach-Object { Rename-Item $_ $_.replace(" ","_") }
Error message:
Rename-Item : Source and destination path must be different. At line:1
char:60
+ Get-ChildItem -recurse -name | ForEach-Object { Rename-Item <<<< $_ $.replace(" ","") }
+ CategoryInfo : WriteError: (PATH_HERE) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
How I should improve this short code?
Don't use the Name switch, it outputs only the names of the objects, not their full path. Try this:
Get-ChildItem -Recurse | `
Where-Object {$_.Name -match ' '} | `
Rename-Item -NewName { $_.Name -replace ' ','_' }
The issue here is that if there is no space in the file name the name does not change. This is not supported by Rename-Item. You should use Move-Item instead:
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }
Additionally, in your answer you missed the underscore in $_.replace(...) plus you where replacing spaces with an empty string. Included this in my answer.
Adding a filter worked for me:
Get-ChildItem C:\path-to-directory -Recurse -Filter *foo* | Rename-Item -NewName { $_.name -replace 'foo', 'bar'} -verbose