我有一个文件目录,只要它们没有现有的指定扩展名,我想将文件扩展名附加到它们。因此,将 .txt 添加到所有不以 .xyz 结尾的文件名。PowerShell 似乎是一个很好的候选者,但我对此一无所知。我该怎么办?
John Sheehan
问问题
35876 次
4 回答
27
这是Powershell的方式:
gci -ex "*.xyz" | ?{!$_.PsIsContainer} | ren -new {$_.name + ".txt"}
或者让它更冗长,更容易理解:
Get-ChildItem -exclude "*.xyz"
| WHere-Object{!$_.PsIsContainer}
| Rename-Item -newname {$_.name + ".txt"}
编辑:DOS方式当然也没有错。:)
EDIT2:Powershell 确实支持隐式(和显式)行继续,正如马特汉密尔顿的帖子所示,它确实使事情更容易阅读。
于 2008-10-30T21:45:40.920 回答
16
+1 EBGreen,除了(至少在 XP 上)get-childitem 的“-exclude”参数似乎不起作用。帮助文本 (gci -?) 实际上说“此参数在此 cmdlet 中无法正常工作”!
所以你可以像这样手动过滤:
gci
| ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") }
| %{ ren -new ($_.Name + ".txt") }
于 2008-10-30T21:48:32.710 回答
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
于 2008-10-30T21:32:28.280 回答
2
在使用 PowerShell v4 时发现这很有帮助。
Get-ChildItem -Path "C:\temp" -Filter "*.config" -File |
Rename-Item -NewName { $PSItem.Name + ".disabled" }
于 2015-05-16T21:37:38.680 回答