繁体   English   中英

使用PowerShell为文件添加扩展名

[英]Using PowerShell to add an extension to files

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

以下是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到EBGreen,除了(至少在XP上)get-childitem的“-exclude”参数似乎不起作用。 帮助文本(gci - ?)实际上说“此参数在此cmdlet中无法正常工作”!

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

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

在标准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

使用PowerShell v4时发现这很有用。

Get-ChildItem -Path "C:\temp" -Filter "*.config" -File | 
    Rename-Item -NewName { $PSItem.Name + ".disabled" }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM