Home > Back-end >  Can't Move-Item Modified file
Can't Move-Item Modified file

Time:11-11

I was trying to follow the solution given by @StephenP in this post: Renaming and Moving Files Powershell

I am trying to Move a renamed file to the Output Folder, but it didn't move. What could go wrong?

Here's my code:

$Files = GCI "$ParentFolder" | ?{$_.Extension -Match "png?"}
$Date = Get-Date -Format "yyyymmddhhmmss"
$Dest = ".\Output"

$Files | ForEach-Object {

    # Get the File BaseName and Select the Screen Title only
    $FileName = $_.BaseName
    $NameCount = $FileName.length
    $ScreenTitle = $FileName.substring(0,$NameCount -21)

    # Set the New File Name as Variable
    $NewFileName = "$($Date)_[$($ScreenTitle)]"

    # Start Renaming
    $GetName = $_.FullName -replace "$FileName","$NewFileName"
    Rename-Item $_ $GetName

    # Move the renamed file 
    Move-Item $GetName -Destination $Dest
}

Thank you for helping :)

CodePudding user response:

First of all, you don't need to rename the file first and then move, because you can do this using Move-Item at the same time.

Use -Filter '*.png' instead of a Where-Object afterwards. The Filter is much more efficient.

Your code does not check if the length of the file BaseName is actually more than 21 characters long, so this $FileName.Substring(0, $NameCount -21) can throw exceptions. However, since you didn't provide any filename examples, I left that in.

Try

$Files = Get-ChildItem -Path $ParentFolder -Filter '*.png' -File
$Date  = Get-Date -Format "yyyymmddhhmmss"
$Dest = ".\Output"

$Files | ForEach-Object {
    # Get the File BaseName and Select the Screen Title only
    $FileName    = $_.BaseName
    $NameCount   = $FileName.Length
    # very tricky this.. could throw error if $FileName is less than 21 characters..
    $ScreenTitle = $FileName.Substring(0, $NameCount -21)  

    # Set the New File Name as Variable
    $NewFileName = '{0}_[{1}]{2}' -f  $Date, $ScreenTitle, $_.Extension

    # Move the file with a new name to the destination
    $_ | Move-Item -Destination (Join-Path -Path $Dest -ChildPath $NewFileName)
}

As aside, using square brackets in filenames could cause you problems and to do more PowerShell on these files, you need to always remember to use -LiteralPath instead of -Path on cmdlets that support it like Get-ChildItem

  • Related