Windows脚本循环

我是新来的Windows脚本。 我写了一个小batch file来移动一个大目录中的子目录和文件。

@ECHO OFF for /f %x in ('dir /ad /b') do move %xipad %x\ for /f %x in ('dir /ad /b') do md %x\thumbs for /f %x in ('dir /ad /b') do move %x\*thumb.png %x\thumbs\ for /f %x in ('dir /ad /b') do move %x\*thumb.jpg %x\thumbs\ for /f %x in ('dir /ad /b') do del %x\%xipad\*thumb.png for /f %x in ('dir /ad /b') do del %x\%xipad\*thumb.jpg for /f %x in ('dir /ad /b') do del %x\xml.php for /f %x in ('dir /ad /b') do del %x\%xipad\xml.php 

看起来我可以把所有的命令放在一个单独的“for / f%x in …”循环中,然后执行里面的逻辑。 我可能应该检查,如果扩展名是.png或.jpg(而不是两个单独的命令)。 做这两个动作的最好方法是什么? 另外还有什么我应该实施,以使这个更好?

PowerShell在这个例子中看起来更加冗长,但是这里是一个例子。 同样,正如我在我的评论中提到的那样 – 如果您现在正在尝试为Windows学习脚本语言,请帮助自己并学习PowerShell!

 #Get the directories we're going to work with: Get-ChildItem -Path d:\rootdirectory\ | ? {$_.PSIsContainer} | % { #Remove all xml.php files from current directory and current directory ipad. Remove-Item ($_.FullName + "\xml.php") #For all the files in the directory move the each "ipad" directory into the directory with the same name. If ($_.Name -like *ipad) { #Delete all png and jpg images with "thumb" in the name from each current directories ipad directory Get-ChildItem $_ -filter "*thumb* | ? {($_.Extension -eq "jpg") -or ($_.Extension -eq "png")} | % { Remove-Item $_ } #...Then actually move the item Move-Item $_ -Destination $_.FullName.Replace("ipad","")} } #Use else to work on the remainder of the directories: else { #Create a directory called "thumbs" inside all of the current directories $thumbDir = New-Item -ItemType Directory -Path ($_.FullName + "\thumbs\") #Move all png and jpg files in the current directory with "thumb" in the name into the "thumbs" directory. Get-ChildItem $_ -filter "*thumb* | ? {($_.Extension -eq "jpg") -or ($_.Extension -eq "png")} | % { Move-Item $_ -Destination $thumbDir.FullName } } 

只需要按照以下方法做一个for循环:

 for /D %%x in (*) do ( move %%xipad %%x\ md %%x\thumbs move %%x\*thumb.png %x\thumbs\ move %%x\*thumb.jpg %x\thumbs\ del %%x\%%xipad\*thumb.png del %%x\%%xipad\*thumb.jpg del %%x\xml.php del %%x\%%xipad\xml.php ) 

请注意,您必须在这些变量的批处理文件中使用双精度% 。 正如你注意到的,你不需要遍历dir输出,因为可以遍历文件和目录就好了。

至于检查扩展我有点茫然你要检查什么扩展,具体来说。 您正在遍历文件夹,但文件夹上的扩展名很少有任何意义。