Powershell Move-Item Rename If File Exists

后端 未结 2 624
Happy的楠姐
Happy的楠姐 2020-12-17 07:12

I have a powershell script that takes all of the files in one directory, renames the first one and moves it, and then goes to the next file. Sometimes there will be multiple

2条回答
  •  天命终不由人
    2020-12-17 07:55

    There's no built-in way to do that. Give this a try:

    $src = "d:\temp"
    $dest = "d:\temp1"
    $num=1
    
    Get-ChildItem -Path $src -Filter *.txt -Recurse | ForEach-Object {
    
        $nextName = Join-Path -Path $dest -ChildPath $_.name
    
        while(Test-Path -Path $nextName)
        {
           $nextName = Join-Path $dest ($_.BaseName + "_$num" + $_.Extension)    
           $num+=1   
        }
    
        $_ | Move-Item -Destination $nextName
    }
    

提交回复
热议问题