Shorten a filename after a copy-item command

Welcome Forums General PowerShell Q&A Shorten a filename after a copy-item command

This topic contains 1 reply, has 2 voices, and was last updated by

2 years, 11 months ago.

  • Author
  • #44269

    Topics: 1
    Replies: 0
    Points: 0
    Rank: Member


    I'm copying xml files from one directory to another using Windows Task Scheduler. The xml filenames generated by a software are quite long. Is there a way to shorten the filename to 8-10 characters?

    This is the command I'm using in my script to copy xml files:

     Get-ChildItem -Filter *.xml $SrcDir | Where-Object{$_.LastWriteTime -gt $LastDate} | Copy-Item -Destination $DestDir 

    Thanks in advance!

  • #44275

    Topics: 6
    Replies: 652
    Points: 11
    Rank: Member

    Hey Richard, there are a unknowns to your question like, how are you going to derive the new file name? Is it based on the current file name? Is it just a crop of the current file name? Is it some totally new file name? Is the new file name based on current date/time? etc, etc, etc.

    With that said, here is an example that just takes the first 8 characters of the existing file name to use for the rename.

    Get-ChildItem -Filter *.xml $SrcDir | 
    Where-Object{$_.LastWriteTime -gt $LastDate} | 
    Copy-Item -Destination $DestDir -PassThru | 
    Rename-Item -NewName {"$($PSItem.BaseName.substring(0,8))$($PSItem.Extension)"}

The topic ‘Shorten a filename after a copy-item command’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort