- Text Editor inside PowerShell
- Работа с файлами и папками Working with Files and Folders
- Получение списка файлов и папок, содержащихся в папке Listing All the Files and Folders Within a Folder
- Копирование файлов и папок Copying Files and Folders
- Создание файлов и папок Creating Files and Folders
- Удаление всех файлов и папок, содержащихся в папке Removing All Files and Folders Within a Folder
- Подключение локальной папки как диска Mapping a Local Folder as a drive
- Чтение текстового файла в массив Reading a Text File into an Array
- Windows Shell
- Shell Development Scenarios
- Windows Shell SDK Documentation
Text Editor inside PowerShell
If you’ve ever groaned about having to leave PowerShell just to edit a file, I have good news for you.
I come from a background of having a text editor at my fingertips while doing work in the command-line. If I needed to edit a file, I would simply type “vi filename”, and I would edit the file within Vim (text editor included with most Linux systems), then exit Vim, and be right back at the command-line without skipping a beat. Normally, in order to edit a file while using PowerShell, you need to interrupt your flow by running something like “notepad filename”, which takes you back to the land of GUI’s and mice (oh the horror!), you edit your file, then go back to the command-line land of PowerShell.
Granted this problem that I have an easy solution to, is probably not a huge issue for many people. But, I think there is something to be said for streamlining your workflow, even if it’s a small adjustment (they add up). Being a systems administrator, I’m always looking for tricks and tools to automate and streamline my repetitive processes.
Without further ado, I’ll jump straight to the solution. This does require having “ Bash on Windows” installed. This is also referred to as “Bash on Ubuntu on Windows”. Essentially Bash on Windows allows you to run a Linux environment, including the Bash shell, on Windows. Read more about it here: https://msdn.microsoft.com/en-us/commandline/wsl/about. This site also includes installation instructions.
Now from PowerShell, all you have to do is run:
If this is your first time running Vim, you will definitely want to check out the resources at the end of this article before diving in. I’ll suffice it to say that inserting text and even exiting the program require learning. Don’t let these things discourage you from trying though, you’ll be rewarded handsomely in efficiency, if you stick with it.
If you would just like to edit a file without any learning curve, then Nano, which is another command-line text editor, may be a good choice for you. If so, run:
Something which may trip you up with Nano, is that the “^” in the keyboard shortcuts at the bottom of the screen is the “Ctrl” key. So “^O” is “Ctrl+o”. Also “^O” is labeled as “WriteOut”, this is the same as Save.
After you edit the file you’re working on, simply save it and and exit, and you’ll be right back to Powershell. You don’t need to run “bash” to go to Linux, then use Vim or Nano, then “exit” to go back to PowerShell.
This command works with both new files that you want to create and editing existing ones. For new files, it will create the file in whatever directory you are in when you run the command. For existing files, you have to use the Linux file path convention, which would look like this:
bash -c “vi /mnt/c/Users/username/Documents/filename.txt”
This is truly all there is to it. It’s so simple that it may even seem like it doesn’t warrant a blog post. I believe it does warrant a post though, especially for the Windows PowerShell users who have little or no Linux experience. Hopefully it opens up a new world of command-line text editors that some didn’t even know existed. For some, like myself, who have used command-line text editors, it will show them how they can be easily harnessed from PowerShell.
If you want to go one step further in efficiency, then Google “PowerShell profile”. Once you figure out what and where the powershell profile files are and which one you should edit, then add the following function to it and you’ll be one step further in your road to efficiency:
#Below function updated 6/22/2018 from EUNJIN LEE’s comment to allow for use of tab completion ($File = $File -replace “\\”, “/”)
#Below function was updated 3/27/2019 from Brendon Thiede’s comment regarding handling spaces in filenames (-replace “ “, “\ “)
function vi ($File)<
$File = $File -replace “\\”, “/” -replace “ “, “\ “
bash -c “vi $File”
>
Now every time you want to edit a file you can just run:
The same function and command will work with Nano as well.
Работа с файлами и папками Working with Files and Folders
Просмотр содержимого дисков Windows PowerShell и управление хранящимися на них элементами аналогично управлению файлами и папками на физических дисках Windows. Navigating through Windows PowerShell drives and manipulating the items on them is similar to manipulating files and folders on Windows physical disk drives. В этой статье описывается выполнение конкретных задач по управлению файлами и папками с помощью PowerShell. This article discusses how to deal with specific file and folder manipulation tasks using PowerShell.
Получение списка файлов и папок, содержащихся в папке Listing All the Files and Folders Within a Folder
Извлечь все элементы непосредственно из папки можно с помощью командлета Get-ChildItem . You can get all items directly within a folder by using Get-ChildItem . Для отображения скрытых и системных элементов добавьте необязательный параметр Force . Add the optional Force parameter to display hidden or system items. Например, эта команда отображает непосредственное содержимое диска C Windows PowerShell (которое совпадает с содержимым физического диска C Windows): For example, this command displays the direct contents of Windows PowerShell Drive C (which is the same as the Windows physical drive C):
Эта команда выводит только элементы, содержащиеся на диске непосредственно, так же как и команда DIR оболочки Cmd.exe или команда ls оболочки UNIX. The command lists only the directly contained items, much like using Cmd.exe ‘s DIR command or ls in a UNIX shell. Для показа вложенных элементов необходимо также указать параметр -Recurse . In order to show contained items, you need to specify the -Recurse parameter as well. (Время выполнения этой операции будет очень велико.) Для вывода всего содержимого диска C введите: (This can take an extremely long time to complete.) To list everything on the C drive:
Командлет Get-ChildItem позволяет отфильтровать элементы с помощью параметров Path , Filter , Include и Exclude , но обычно осуществляется лишь фильтрация по имени. Get-ChildItem can filter items with its Path , Filter , Include , and Exclude parameters, but those are typically based only on name. Сложную фильтрацию на основе других свойств элементов можно выполнить с помощью Where-Object . You can perform complex filtering based on other properties of items by using Where-Object .
Следующая команда находит все исполняемые файлы в папке Program Files, которые были в последний раз изменены после 1 октября 2005 г. и размер которых не менее одного мегабайта и не более десяти мегабайт: The following command finds all executables within the Program Files folder that were last modified after October 1, 2005 and which are neither smaller than 1 megabyte nor larger than 10 megabytes:
Копирование файлов и папок Copying Files and Folders
Копирование выполняется с помощью командлета Copy-Item . Copying is done with Copy-Item . Следующая команда создает резервную копию C:\boot.ini в C:\boot.bak: The following command backs up C:\boot.ini to C:\boot.bak:
Если целевой файл уже существует, то попытка копирования завершается неудачей. If the destination file already exists, the copy attempt fails. Чтобы перезаписать имеющийся целевой файл, используйте параметр Force . To overwrite a pre-existing destination, use the Force parameter:
Эта команда работает, даже если целевой объект доступен только для чтения. This command works even when the destination is read-only.
Так же выполняется и копирование папок. Folder copying works the same way. Эта команда копирует папку C:\temp\test1 в новую папку C:\temp\DeleteMe рекурсивно. This command copies the folder C:\temp\test1 to the new folder C:\temp\DeleteMe recursively:
Можно также скопировать избранные элементы. You can also copy a selection of items. Следующая команда копирует все файлы TXT, содержащиеся в папке C:\data , в папку C:\temp\text : The following command copies all .txt files contained anywhere in C:\data to C:\temp\text :
Для копирования элементов файловой системы можно использовать и другие средства. You can still use other tools to perform file system copies. В Windows PowerShell по-прежнему работают команды XCOPY, ROBOCOPY и такие COM-объекты, как Scripting.FileSystemObject . XCOPY, ROBOCOPY, and COM objects, such as the Scripting.FileSystemObject, all work in Windows PowerShell. Например, можно воспользоваться COM-классом Scripting.FileSystem сервера сценариев Windows для создания резервной копии файла C:\boot.ini в файле C:\boot.bak : For example, you can use the Windows Script Host Scripting.FileSystem COM class to back up C:\boot.ini to C:\boot.bak :
Создание файлов и папок Creating Files and Folders
Создание новых элементов осуществляется одинаковым образом всеми поставщиками Windows PowerShell. Creating new items works the same on all Windows PowerShell providers. Если поставщик Windows PowerShell поддерживает более одного типа элементов (например, поставщик Windows PowerShell FileSystem различает каталоги и файлы), необходимо указать тип элемента. If a Windows PowerShell provider has more than one type of item—for example, the FileSystem Windows PowerShell provider distinguishes between directories and files—you need to specify the item type.
Эта команда создает папку C:\temp\New Folder : This command creates a new folder C:\temp\New Folder :
Эта команда создает пустой файл C:\temp\New Folder\file.txt . This command creates a new empty file C:\temp\New Folder\file.txt
При использовании параметра Force с командой New-Item для создания папки, которая уже существует, она не перезапишет и не заменит папку. When using the Force switch with the New-Item command to create a folder, and the folder already exists, it won’t overwrite or replace the folder. Будет просто возвращен имеющийся объект папки. It will simply return the existing folder object. Однако, если использовать New-Item -Force в уже имеющимся файле, файл будет полностью перезаписан. However, if you use New-Item -Force on a file that already exists, the file will be completely overwritten.
Удаление всех файлов и папок, содержащихся в папке Removing All Files and Folders Within a Folder
Удалить вложенные элементы можно с помощью командлета Remove-Item , однако он потребует подтверждения удаления, если элемент сам что-нибудь содержит. You can remove contained items using Remove-Item , but you will be prompted to confirm the removal if the item contains anything else. Например, при попытке удаления папки C:\temp\DeleteMe , которая содержит другие элементы, Windows PowerShell предварительно предложит подтвердить удаление этой папки: For example, if you attempt to delete the folder C:\temp\DeleteMe that contains other items, Windows PowerShell prompts you for confirmation before deleting the folder:
Если подтверждение для каждого вложенного элемента нежелательно, задайте параметр Recurse : If you do not want to be prompted for each contained item, specify the Recurse parameter:
Подключение локальной папки как диска Mapping a Local Folder as a drive
Отобразить локальную папку можно с помощью команды New-PSDrive . You can also map a local folder, using the New-PSDrive command. Следующая команда создает локальный диск P: , корневым каталогом которого является локальный каталог Program Files, отображающийся только в сеансе PowerShell: The following command creates a local drive P: rooted in the local Program Files directory, visible only from the PowerShell session:
Как и при использовании сетевых дисков, диски, отображенные в Windows PowerShell, немедленно становятся доступными оболочке Windows PowerShell. Just as with network drives, drives mapped within Windows PowerShell are immediately visible to the Windows PowerShell shell. Чтобы создать подключенный диск, отображающийся в проводнике, нужен параметр -Persist . In order to create a mapped drive visible from File Explorer, the parameter -Persist is needed. Но с этим параметром можно использовать только удаленные пути. However, only remote paths can be used with Persist.
Чтение текстового файла в массив Reading a Text File into an Array
Одним из наиболее общих форматов хранения текстовых данных является файл, отдельные строки которого рассматриваются как отдельные элементы. One of the more common storage formats for text data is in a file with separate lines treated as distinct data elements. Командлет Get-Content используется для чтения всего файла за один шаг, как показано далее: The Get-Content cmdlet can be used to read an entire file in one step, as shown here:
Командлет Get-Content сразу рассматривает данные, считанные из файла, как массив с одним элементом на строку содержимого файла. Get-Content already treats the data read from the file as an array, with one element per line of file content. Убедиться в этом можно, проверив свойство Length полученного содержимого: You can confirm this by checking the Length of the returned content:
Эта команда наиболее полезна для непосредственного ввода в Windows PowerShell информационных списков. This command is most useful for getting lists of information into Windows PowerShell directly. Например, можно хранить в файле C:\temp\domainMembers.txt список имен компьютеров или IP-адресов по одному имени на каждую строку файла. For example, you might store a list of computer names or IP addresses in a file C:\temp\domainMembers.txt , with one name on each line of the file. Вы можете использовать командлет Get-Content , чтобы извлечь содержимое файла и поместить его в переменную $Computers : You can use Get-Content to retrieve the file contents and put them in the variable $Computers :
Теперь переменная $Computers представляет собой массив, содержащий в каждом элементе имя компьютера. $Computers is now an array containing a computer name in each element.
Windows Shell
The Windows UI provides users with access to a wide variety of objects necessary for running applications and managing the operating system. The most numerous and familiar of these objects are the folders and files that reside on computer disk drives. There are also a number of virtual objects that allow the user to perform tasks such as sending files to remote printers or accessing the Recycle Bin. The Shell organizes these objects into a hierarchical namespace and provides users and applications with a consistent and efficient way to access and manage objects.
Shell Development Scenarios
The following development scenarios relate to application development:
- Extending the Shell, which consists of creating a data source (versus consuming the Shell data model)
- Implementing a subset of the Shell data source tasks
- Supporting libraries and item views in Windows Explorer
- Using the common file dialog
- Implementing Control Panel items
- Managing notifications
The following development scenarios relate to file format ownership:
- Implementing a subset of the Shell data source tasks
- Implementing any handler
- Supporting desktop search
The following development scenarios relate to data storage ownership:
- Supporting desktop search and OpenSearch
- Implementing a subset of the Shell data source tasks (virtual folders)
- Supporting libraries in Windows Explorer
The following development scenario relates to device support:
- Auto run and auto play
Windows Shell SDK Documentation
This documentation is broken into three major sections:
- The Shell Developer’s Guide provides conceptual material about how the Shell works and how to use the Shell’s API in your application.
- The Shell Reference section documents programming elements that make up the various Shell APIs.
- Shell Samples provides links to related code samples.
The following table provides an outline of the Shell Reference section. Unless otherwise noted, all programming elements are documented in unmanaged C++.