使用PowerShell为文件添加扩展名

Joh*_*han 14 powershell

我有一个文件目录,我想附加文件扩展名,只要它们没有现有的指定扩展名.因此,将.txt添加到所有不以.xyz结尾的文件名中.PowerShell似乎是一个很好的候选人,但我对此一无所知.我该怎么办呢?

EBG*_*een 22

以下是Powershell方式:

gci -ex "*.xyz" | ?{!$_.PsIsContainer} | ren -new {$_.name + ".txt"}
Run Code Online (Sandbox Code Playgroud)

或者使它更冗长,更容易理解:

Get-ChildItem -exclude "*.xyz" 
    | WHere-Object{!$_.PsIsContainer} 
    | Rename-Item -newname {$_.name + ".txt"}
Run Code Online (Sandbox Code Playgroud)

编辑:DOS方式当然没有任何问题.:)

EDIT2:Powershell确实支持隐式(并明确表示)行延续,而Matt Hamilton的帖子显示它确实使事情更容易阅读.


Mat*_*ton 16

+1到EBGreen,除了(至少在XP上)get-childitem的"-exclude"参数似乎不起作用.帮助文本(gci - ?)实际上说"此参数在此cmdlet中无法正常工作"!

所以你可以像这样手动过滤:

gci 
  | ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") } 
  | %{ ren -new ($_.Name + ".txt") }
Run Code Online (Sandbox Code Playgroud)