Forum Discussion

zhmizi520's avatar
zhmizi520
Copper Contributor
Oct 06, 2024

Question about ‘get-childitem | rename-item’ have a bug

If i have 20 .txt file 。

 

1..20 | foreach-object {new-item -type file .\$_.txt}
get-childitem | rename-item -newname {"newfile$_"}

 

 You will get picture 1 .

But if you have 50 .txt file . you will have a bug.

 

1..50 | foreach-object {new-item -type file .\$_.txt}
get-childitem | rename-item -newname {"newfile$_"}

 

Look at picture 2. 

why ??

2 Replies

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    zhmizi520 

     

    The "fault" seems to lie with Get-ChildItem, not Rename-Item.

     

    I'm finding that once I have more than 36 files, Get-ChildItem seems to "page" the fetching of files. The issue there seems to be that the files that have already been renamed between 1 and 36 show up in the next page with their new names, creating a looping issue.

     

    Even if the threshold of 36 can be increased, the paging-like flaw would remain.

     

    While far from ideal, the only way I can see to get around this is to assign the files to a variable first and then pipe the variable through to Rename-Item. (Storing large result sets in variables instead of using the pipeline is dreadful.)

     

    # Silently stage 37 files.
    1..37 | ForEach-Object { New-Item -Type File -Name "$_.txt" } | Out-Null;
    
    # Assign to a variable.
    $files = Get-ChildItem -File;
    
    # Rename.
    $files | Rename-Item -NewName { "newname$_" };
    
    # Check the first ten files.
    Get-ChildItem -File | Select-Object -First 10;

     

     

    I'm reluctant to call this a bug, but I would call it a design flaw.

     

    Cheers,

    Lain

     

    • zhmizi520's avatar
      zhmizi520
      Copper Contributor
      Thank you for you reply ! so quickly!
      Thank you very much !
      You are so kindly !

Resources