Powershell Move-Item Rename If File Exists

后端 未结 2 625
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:48
    #Fixed solution basing on previous answer (variable $num moved into for each loop):
    
    $src = "d:\temp"
    $dest = "d:\temp1"
    
    Get-ChildItem -Path $src -Filter *.txt -Recurse | ForEach-Object {
        $num=1
        $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
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题