У меня есть каталог файлов, которые я бы хотел добавить к расширению файла до тех пор, пока у них нет существующего указанного расширения. Поэтому добавьте .txt ко всем именам файлов, которые не заканчиваются на .xyz. PowerShell кажется хорошим кандидатом на это, но я ничего не знаю об этом. Как я могу это сделать?
Использование PowerShell для добавления расширения к файлам
Ответ 1
+1 до EBGreen, за исключением того, что (по крайней мере, на XP) параметр "-exclude" для get-childitem не работает. Текст справки (gci -?) На самом деле говорит: "Этот параметр не работает должным образом в этом командлете"!
Итак, вы можете фильтровать вручную, как это:
gci
| ?{ !$_.PSIsContainer -and !$_.Name.EndsWith(".xyz") }
| %{ ren -new ($_.Name + ".txt") }
Ответ 2
Вот путь Powershell:
gci -ex "*.xyz" | ?{!$_.PsIsContainer} | ren -new {$_.name + ".txt"}
Или сделать это немного более подробным и понятным:
Get-ChildItem -exclude "*.xyz"
| WHere-Object{!$_.PsIsContainer}
| Rename-Item -newname {$_.name + ".txt"}
РЕДАКТИРОВАТЬ: Разумеется, нет ничего плохого в использовании DOS.:)
EDIT2: Powershell действительно поддерживает неявное (и прямое) продолжение линии, и, как показывает сообщение Мэтта Гамильтона, это облегчает чтение.
Ответ 3
Рассмотрим 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
Ответ 4
Обнаружено, что это полезно при использовании PowerShell v4.
Get-ChildItem -Path "C:\temp" -Filter "*.config" -File |
Rename-Item -NewName { $PSItem.Name + ".disabled" }