Удалить файлы по маске powershell
Я хочу удалить все файлы из структуры папок, поэтому у меня осталась пустая структура папок.
Это может быть достигнуто в пакетном или VBScript сценариях?
Я пробовал очень простую пакетную команду, но для этого требовалось, чтобы пользователь разрешил удаление каждого файла. Это не подходящее решение, так как существует много сотен файлов, и со временем оно значительно увеличится.
Что вы можете предложить?
Вы имеете в виду рекурсивное удаление? Это действительно может быть сделано. Нечто подобное rd /s /q "c:\folder a выполнит рекурсивное удаление всех файлов и папок внутри Folder A
Я мог бы сделать, я не знаю, как писать сценарии в powershell, но у меня были сценарии powershell для предыдущего запуска.
Сейчас самое подходящее время для изучения, я бы исследовал синтаксис batch и vbs для унаследованных целей, но потратил больше времени на изучение PS.
У меня еще не было возможности проверить код, хотя я уверен, что он будет работать. Я вернусь и выберу наиболее подходящий ответ на мой первоначальный запрос.
Я буду второй рекомендацией BigHomie - я только что изучил PowerShell и должен сказать, что он довольно аккуратный - не слишком сложный, хорошее оружие в арсенале любого кодера. Я использую это довольно часто сейчас.
Это можно сделать с помощью PowerShell :
Эта команда получает каждый дочерний элемент $path , выполняет метод удаления для каждого элемента и работает довольно быстро. Структура папок осталась нетронутой.
Если у вас могут быть файлы без расширения, используйте
Похоже, что -File параметр мог быть добавлен после PowerShell v2. Если это так, то
Это должно сделать трюк для файлов с расширением.
Они не могут реализовать powershell --version ? Разве они не могут использовать номер версии с положительными цифрами? Это просто безумие. Более 1300 голосов за вопрос о том, как узнать номер версии программы?
Короткая и удобная PowerShell. Не уверен, с какой низшей версией PS он будет работать.
Это должен быть принятый ответ, вы можете даже просто напечатать, rm * так как на самом деле не рекомендуется форсировать (в любом случае в диалоговом окне подтверждения есть опция «Да для всех»).
Вы можете сделать это с помощью del команды:
/S Переключатель , чтобы удалить только файлы рекурсивно.
Да. Вы можете добавить /P опцию, чтобы она попросила вас подтвердить каждое удаление, чтобы проверить это.
Да. А для удаления скрытых и системных файлов сделайте attrib -s -r -h Folder\*.* /s /d перед удалением. А для разрешений используйте takeown команду.
И вы можете использовать / Q, чтобы НЕ запрашивать подтверждение при использовании подстановочных знаков.
Читая между строк вашего исходного вопроса, я могу предложить альтернативную строку кода BATCH, которую вы можете использовать. При запуске будут удалены только файлы старше 60 дней. Таким образом, вы можете поместить это в запланированное задание, и при запуске оно удалит лишние файлы, которые вам не нужны, вместо того, чтобы уничтожить весь каталог. Вы можете изменить от 60 до 5 дней или даже 1 день, если хотите. Это не удаляет папки.
Спасибо за идею, но в настоящее время я думаю, что процесс «опорожнения» будет завершен в очень незапланированные временные рамки. Я оставлю этот код на будущее! Приветствия
Используйте PowerShell для удаления отдельного файла или папки. Перед выполнением команды Delete в powershell мы должны убедиться, что вы вошли на сервер или ПК с учетной записью, которая имеет полный доступ к объектам, которые вы хотите удалить.
Remove-Item -Path "C: \ dotnet-helpers \ DummyfiletoDelete.txt"
Приведенная выше команда выполнит и удалит файл «DummyfiletoDelete.txt», который находится внутри папки «C: \ dotnet-helpers».
Remove-Item -Path "C: \ dotnet-helpers *. *" -Recurse
-recurse сверлит вниз и находит намного больше файлов. Этот –recurse параметр позволит PowerShell удалять любые дочерние элементы без запроса разрешения. Кроме того, параметр –force может быть добавлен для удаления скрытых или доступных только для чтения файлов.
Использование команды -Force для принудительного удаления файлов
Remove-Item -Path "C: \ dotnet-helpers *. *" -Force
The Remove-Item cmdlet deletes one or more items. Because it is supported by many providers, it can delete many different types of items, including files, folders, registry keys, variables, aliases, and functions.
Examples
Example 1: Delete files that have any file name extension
This example deletes all of the files that have names that include a dot ( . ) from the C:\Test folder. Because the command specifies a dot, the command does not delete folders or files that have no file name extension.
Example 2: Delete some of the document files in a folder
This example deletes from the current folder all files that have a .doc file name extension and a name that does not include *1* .
It uses the wildcard character ( * ) to specify the contents of the current folder. It uses the Include and Exclude parameters to specify the files to delete.
Example 3: Delete hidden, read-only files
This command deletes a file that is both hidden and read-only.
It uses the Path parameter to specify the file. It uses the Force parameter to delete it. Without Force, you cannot delete read-only or hidden files.
Example 4: Delete files in subfolders recursively
This command deletes all of the CSV files in the current folder and all subfolders recursively.
Because the Recurse parameter in Remove-Item has a known issue, the command in this example uses Get-ChildItem to get the desired files, and then uses the pipeline operator to pass them to Remove-Item .
In the Get-ChildItem command, Path has a value of ( * ), which represents the contents of the current folder. It uses Include to specify the CSV file type, and it uses Recurse to make the retrieval recursive. If you try to specify the file type the path, such as -Path *.csv , the cmdlet interprets the subject of the search to be a file that has no child items, and Recurse fails.
This behavior was fixed in Windows versions 1909 and up.
Example 5: Delete subkeys recursively
This command deletes the "OldApp" registry key and all its subkeys and values. It uses Remove-Item to remove the key. The path is specified, but the optional parameter name (Path) is omitted.
The Recurse parameter deletes all of the contents of the "OldApp" key recursively. If the key contains subkeys and you omit the Recurse parameter, you are prompted to confirm that you want to delete the contents of the key.
Example 6: Deleting files with special characters
The following example shows how to delete files that contain special characters like brackets or parentheses.
Example 7: Remove an alternate data stream
This example shows how to use the Stream dynamic parameter of the Remove-Item cmdlet to delete an alternate data stream. The stream parameter is introduced in Windows PowerShell 3.0.
The Stream parameter Get-Item gets the Zone.Identifier stream of the Copy-Script.ps1 file. Remove-Item uses the Stream parameter to remove the Zone.Identifier stream of the file. Finally, the Get-Item cmdlet shows that the Zone.Identifier stream was deleted.
Parameters
Prompts you for confirmation before running the cmdlet. For more information, see the following articles:
This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.
Type: | PSCredential |
Position: | Named |
Default value: | Current user |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt . Wildcard characters are permitted. The Exclude parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.
When using Recurse with Exclude, Exclude only filters results of the current directory. If there are files that match the Exclude pattern in subfolders, those files are removed along with its parent directory.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a filter to qualify the Path parameter. The FileSystem provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the FileSystem filter language in about_Wildcards. Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Forces the cmdlet to remove items that cannot otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet cannot remove constant aliases or variables. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.
Type: | SwitchParameter |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcard characters are permitted. The Include parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a path to one or more locations. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies a path of the items being removed. Wildcard characters are permitted.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Indicates that this cmdlet deletes the items in the specified locations and in all child items of the locations.
The Recurse parameter might not delete all subfolders or all child items. This is a known issue.
This behavior was fixed in Windows versions 1909 and newer.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This Parameter is only available on Windows.
The Stream parameter is a dynamic parameter that the FileSystem provider adds to Remove-Item . This parameter works only in file system drives.
You can use Remove-Item to delete an alternative data stream, such as Zone.Identifier . However, it is not the recommended way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the Unblock-File cmdlet.
This parameter was introduced in Windows PowerShell 3.0. As of Windows PowerShell 7.2, Remove-Item can remove alternative data streams from directories as well as files.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
None
This cmdlet does not return any output.
Notes
The Remove-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type Get-PsProvider . For more information, see about_Providers.
When you try to delete a folder that contains items without using the Recurse parameter, the cmdlet prompts for confirmation. Using -Confirm:$false does not suppress the prompt. This is by design.
The Remove-Item cmdlet deletes one or more items. Because it is supported by many providers, it can delete many different types of items, including files, folders, registry keys, variables, aliases, and functions.
Examples
Example 1: Delete files that have any file name extension
This example deletes all of the files that have names that include a dot ( . ) from the C:\Test folder. Because the command specifies a dot, the command does not delete folders or files that have no file name extension.
Example 2: Delete some of the document files in a folder
This example deletes from the current folder all files that have a .doc file name extension and a name that does not include *1* .
It uses the wildcard character ( * ) to specify the contents of the current folder. It uses the Include and Exclude parameters to specify the files to delete.
Example 3: Delete hidden, read-only files
This command deletes a file that is both hidden and read-only.
It uses the Path parameter to specify the file. It uses the Force parameter to delete it. Without Force, you cannot delete read-only or hidden files.
Example 4: Delete files in subfolders recursively
This command deletes all of the CSV files in the current folder and all subfolders recursively.
Because the Recurse parameter in Remove-Item has a known issue, the command in this example uses Get-ChildItem to get the desired files, and then uses the pipeline operator to pass them to Remove-Item .
In the Get-ChildItem command, Path has a value of ( * ), which represents the contents of the current folder. It uses Include to specify the CSV file type, and it uses Recurse to make the retrieval recursive. If you try to specify the file type the path, such as -Path *.csv , the cmdlet interprets the subject of the search to be a file that has no child items, and Recurse fails.
This behavior was fixed in Windows versions 1909 and up.
Example 5: Delete subkeys recursively
This command deletes the "OldApp" registry key and all its subkeys and values. It uses Remove-Item to remove the key. The path is specified, but the optional parameter name (Path) is omitted.
The Recurse parameter deletes all of the contents of the "OldApp" key recursively. If the key contains subkeys and you omit the Recurse parameter, you are prompted to confirm that you want to delete the contents of the key.
Example 6: Deleting files with special characters
The following example shows how to delete files that contain special characters like brackets or parentheses.
Example 7: Remove an alternate data stream
This example shows how to use the Stream dynamic parameter of the Remove-Item cmdlet to delete an alternate data stream. The stream parameter is introduced in Windows PowerShell 3.0.
The Stream parameter Get-Item gets the Zone.Identifier stream of the Copy-Script.ps1 file. Remove-Item uses the Stream parameter to remove the Zone.Identifier stream of the file. Finally, the Get-Item cmdlet shows that the Zone.Identifier stream was deleted.
Parameters
Prompts you for confirmation before running the cmdlet. For more information, see the following articles:
This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.
Type: | PSCredential |
Position: | Named |
Default value: | Current user |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt . Wildcard characters are permitted. The Exclude parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.
When using Recurse with Exclude, Exclude only filters results of the current directory. If there are files that match the Exclude pattern in subfolders, those files are removed along with its parent directory.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a filter to qualify the Path parameter. The FileSystem provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the FileSystem filter language in about_Wildcards. Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Forces the cmdlet to remove items that cannot otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet cannot remove constant aliases or variables. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.
Type: | SwitchParameter |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcard characters are permitted. The Include parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a path to one or more locations. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies a path of the items being removed. Wildcard characters are permitted.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Indicates that this cmdlet deletes the items in the specified locations and in all child items of the locations.
The Recurse parameter might not delete all subfolders or all child items. This is a known issue.
This behavior was fixed in Windows versions 1909 and newer.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This Parameter is only available on Windows.
The Stream parameter is a dynamic parameter that the FileSystem provider adds to Remove-Item . This parameter works only in file system drives.
You can use Remove-Item to delete an alternative data stream, such as Zone.Identifier . However, it is not the recommended way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the Unblock-File cmdlet.
This parameter was introduced in Windows PowerShell 3.0.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
None
This cmdlet does not return any output.
Notes
The Remove-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type Get-PsProvider . For more information, see about_Providers.
When you try to delete a folder that contains items without using the Recurse parameter, the cmdlet prompts for confirmation. Using -Confirm:$false does not suppress the prompt. This is by design.
Windows PowerShell использует существительное Item, чтобы ссылаться на элементы, найденные на диске Windows PowerShell. При работе с поставщиком FileSystem Windows PowerShell Item может быть файлом, папкой или диском Windows PowerShell. Создание списков элементов и работа с ними является критически важной задачей в большинстве административных учреждений, поэтому необходимо подробно обсудить ее.
Перечисление файлов, папок и разделов реестра (Get-ChildItem)
Так как получение коллекции элементов из определенного расположения является обычной задачей, командлет Get-ChildItem предназначен специально для возврата всех элементов, найденных в контейнере, например в папке.
Если необходимо вернуть все файлы и папки, которые находятся непосредственно в папке C:\Windows, введите:
Списки выглядят аналогично тем спискам, которые появляются при вводе команды dir в Cmd.exe или команды ls в командной оболочке UNIX.
С помощью параметров командлета Get-ChildItem можно создавать очень сложные списки. Далее рассмотрим несколько сценариев. Синтаксис командлета Get-ChildItem можно увидеть, введя следующее.
Эти параметры можно скомбинировать и сопоставить для получения настраиваемых выходных данных.
Перечисление всех элементов в контейнере (-Recurse)
Чтобы увидеть оба элемента в папке Windows и все элементы во вложенных папках, используйте параметр Recurse для Get-ChildItem . В списке отображается все, что находится в папке Windows, а также элементы в ее вложенных папках. Пример:
Фильтрация элементов по имени (-Name)
Чтобы отобразить только имена элементов, используйте параметр Name для Get-Childitem .
Принудительное перечисление скрытых элементов (-Force)
В выходных данных команды Get-ChildItem не отображаются элементы, которые обычно невидимы в проводнике или Cmd.exe. Чтобы показать скрытые элементы, используйте параметр Force для Get-ChildItem . Пример:
Этот параметр называется Force, так как позволяет принудительно переопределить обычное поведение команды Get-ChildItem . Параметр Force широко используется для принудительного выполнения действия командлетом. Тем не менее, он не будет выполнять действия, компрометирующие систему безопасности.
Сопоставление имен элементов с подстановочными знаками
Команда Get-ChildItem принимает подстановочные знаки в пути к элементам списка.
Так как сопоставление с подстановочными знаками обрабатывается подсистемой Windows PowerShell, все командлеты, которые принимают подстановочные знаки, используют одну нотацию и имеют одно поведение сопоставления. В нотацию подстановочных знаков Windows PowerShell входит:
Звездочка ( * ) соответствует нулю или большему количеству вхождений любого символа.
Знак вопроса ( ? ) соответствует ровно одному символу.
Открывающая квадратная скобка ( [ ) и закрывающая квадратная скобка ( ] ) заключают в себя набор символов для сопоставления.
Далее приводится несколько примеров работы спецификации из подстановочных знаков.
Чтобы найти в каталоге Windows все файлы, имеющие суффикс .log и ровно пять символов в основном имени, введите следующую команду.
Чтобы найти в каталоге Windows все файлы с именами, начинающимися на букву x , введите следующее.
Чтобы найти все файлы с именами, начинающимися на x или z, введите следующее.
Дополнительные сведения о подстановочных знаках см. в разделе about_Wildcards.
Исключение элементов (-Exclude)
Вы можете исключить определенные элементы с помощью параметра Exclude для Get-ChildItem . Это позволит вам выполнить сложную фильтрацию в одном операторе.
Например, вы пытаетесь найти библиотеку службы времени Windows в папке System32 и все, что вам известно об имени библиотеки, — то, что оно начинается с W и содержит 32.
Такое выражение, как w*32*.dll , найдет все библиотеки DLL, которые отвечают этим условиям, но вам может потребоваться дополнительно отфильтровать файлы и пропустить все файлы win32. Эти файлы можно пропустить с помощью параметра Exclude с шаблоном win* .
Смешение параметров Get-ChildItem
В одной команде можно использовать несколько параметров командлета Get-ChildItem . Перед тем как комбинировать параметры, убедитесь, что понимаете принципы сопоставления подстановочных знаков. Например, следующая команда не возвращает результатов:
Результаты отсутствуют, даже если существуют две библиотеки, которые начинаются на букву z в папке Windows.
Результаты не возвращены, так как подстановочный знак указан как часть пути. Хотя команда и была рекурсивной, командлет Get-ChildItem ограничил элементы до тех, которые находятся в папке Windows с именами, заканчивающимися на .dll .
Чтобы указать рекурсивный поиск для файлов, имена которых соответствуют специальному шаблону, используйте параметр Include.
Просмотр содержимого дисков Windows PowerShell и управление хранящимися на них элементами аналогично управлению файлами и папками на физических дисковых накопителях Windows. В этом разделе мы обсудим выполнение отдельных задач управления файлами и папками.
Получение списка файлов и папок, содержащихся в папке
Извлечь все элементы непосредственно из папки можно при помощи командлета Get-ChildItem. Для отображения скрытых и системных элементов добавьте необязательный параметр Force. Например, эта команда отображает непосредственное содержимое диска C Windows PowerShell (которое совпадает с содержимым физического диска C Windows):
Эта команда выводит только элементы, содержащиеся на диске непосредственно, так же как и команда DIR оболочки Cmd.exe или команда ls оболочки UNIX. Для показа вложенных элементов необходимо также указать параметр -Recurse. (Время выполнения этой операции будет очень велико.) Для вывода всего содержимого диска C введите:
Командлет Get-ChildItem позволяет отфильтровать элементы при помощи параметров Path, Filter, Include и Exclude, но обычно осуществляется лишь фильтрация по имени. Сложную фильтрацию на основе других свойств элементов можно выполнить при помощи командлета Where-Object.
Следующая команда находит все исполняемые файлы в папке Program Files, которые были в последний раз изменены после 1 октября 2005 г., и размер которых не менее 1 мегабайта и не более 10 мегабайт:
Копирование файлов и папок
Копирование выполняется при помощи командлета Copy-Item. Следующая команда создает резервную копию C:\boot.bak для файла C:\boot.ini:
Если целевой файл уже существует, то попытка копирования завершается неудачей. Для того чтобы перезаписать существующий целевой файл, используйте параметр Force:
Эта команда работает даже если целевой файл помечен как файл только для чтения.
Так же выполняется и копирование папок. Эта команда рекурсивно копирует папку "C:\temp\test1" в новую папку "c:\temp\DeleteMe":
Можно также скопировать избранные элементы. Следующая команда копирует все файлы .txt, содержащиеся в папке "c:\data", в папку "c:\temp\text":
Для копирования элементов файловой системы можно использовать и другие средства. В Windows PowerShell по-прежнему работают команды XCOPY и ROBOCOPY и такие COM-объекты, как Scripting.FileSystemObject,. Например, можно воспользоваться COM-классом Scripting.FileSystem COM сервера сценариев Windows для создания резервной копии файла C:\boot.ini в файле C:\boot.bak:
Создание файлов и папок
Создание новых элементов осуществляется одинаковым образом всеми поставщиками Windows PowerShell. Если поставщик Windows PowerShell поддерживает более одного типа элементов (например, поставщик Windows PowerShell FileSystem различает каталоги и файлы), необходимо указать тип элемента.
Эта команда создает новую папку "C:\temp\New Folder":
Эта команда создает новый пустой файл "C:\temp\New Folder\file.txt":
Удаление всех файлов и папок, содержащихся в папке
Удалить вложенные элементы можно при помощи командлета Remove-Item, однако он потребует подтверждения удаления, если элемент сам что-нибудь содержит. Например, при попытке удаления папки "C:\temp\DeleteMe", которая содержит другие элементы, Windows PowerShell предварительно предложит подтвердить удаление этой папки:
Если подтверждение для каждого вложенного элемента нежелательно, задайте параметр Recurse:
Отображение локальной папки в виде диска, доступного в Windows
Отобразить локальную папку можно при помощи команды subst. Следующая команда создает локальный диск P:, корневым каталогом которого является локальный каталог Program Files:
Как и в случае сетевых дисков, диски, отображенные в оболочке Windows PowerShell при помощи команды subst, немедленно становятся доступными оболочке Windows PowerShell.
Чтение текстового файла в массив
Одним из наиболее общих форматов хранения текстовых данных является файл, отдельные строки которого рассматриваются как отдельные элементы. Командлет Get-Content используется для чтения всего файла за один шаг, как показано далее:
Командлет Get-Content сразу рассматривает данные, прочитанные из файла, как массив с одним элементом на строку содержимого файла. Убедиться в этом можно, проверив свойство Length полученного содержимого:
Эта команда наиболее полезна для непосредственного ввода в Windows PowerShell информационных списков. Например, можно хранить в файле "C:\temp\domainMembers.txt" список имен компьютеров или IP-адресов по одному имени на каждую строку файла. Можно использовать командлет Get-Content, чтобы извлечь содержимое файла и поместить его в переменную $Computers:
Теперь переменная $Computers представляет собой массив, содержащий в каждом элементе имя компьютера.
Читайте также: