我有一个文件目录,我想附加文件扩展名,只要它们没有现有的指定扩展名。因此,将.txt添加到所有不以.xyz结尾的文件名中。 PowerShell似乎是一个很好的候选者,但我对此一无所知。我该怎么做呢?
答案 0 :(得分:21)
以下是Powershell方式:
gci -ex "*.xyz" | ?{!$_.PsIsContainer} | ren -new {$_.name + ".txt"}
或者使它更冗长,更容易理解:
Get-ChildItem -exclude "*.xyz"
| WHere-Object{!$_.PsIsContainer}
| Rename-Item -newname {$_.name + ".txt"}
编辑:DOS方式当然没有任何问题。 :)
EDIT2:Powershell确实支持隐含(并明确表示)行延续,而Matt Hamilton的帖子显示它确实使事情更容易阅读。
答案 1 :(得分:16)
+1到EBGreen,除了(至少在XP上)get-childitem的“-exclude”参数似乎不起作用。帮助文本(gci - ?)实际上说“此参数在此cmdlet中无法正常工作”!
所以你可以像这样手动过滤:
gci
| ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") }
| %{ ren -new ($_.Name + ".txt") }
答案 2 :(得分:3)
在标准shell中考虑DOS命令FOR。
C:\Documents and Settings\Kenny>help for
Runs a specified command for each file in a set of files.
FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.
...
In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
答案 3 :(得分:2)
使用PowerShell v4时发现这有用。
Get-ChildItem -Path "C:\temp" -Filter "*.config" -File |
Rename-Item -NewName { $PSItem.Name + ".disabled" }