Windows get program files folder

Работа с файлами и папками 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.

Читайте также:  Похоже у вас нет разрешения для просмотра этого файла windows

Так же выполняется и копирование папок. 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.

Читайте также:  Windows loader 221 daz

Чтение текстового файла в массив 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.

Change default Program Files installation directory location in Windows 10

In Windows 10/8/7 OS, by default, software gets installed on your System Drive, usually C drive, in the Program Files folder. The typical path is normally in Windows 32-bit is C:\Program Files and in Windows 64-bit is C:\Program Files and C:\Program Files(x86).

Microsoft recommends the C:\Program Files folder for the default installation destination. It’s a convention that ensures proper inter-operation between your program and the OS’s application and security models. So, once software programs are installed they go by default to C:\Program files on the computer.

This can, however, be changed by selecting another folder or location or partition. To change the default installation folder, the data must be modified in the ProgramFilesDir key and a new path must be chosen for the installation folder.

Windows uses the System Disk for installing any new applications, That is, if your Windows is installed on the C Drive, the default folder where all the applications you install would automatically show up as C:\Program Files, unless of course, you change in manually while installing the application’s locations.

Do note that Microsoft does not support changing the location of the Program Files folder by modifying the ProgramFilesDir registry value. It states that if you change the location of the Program Files folder, you may experience problems with some Microsoft programs or with some software updates.

Change default Program Files directory

If you almost always prefer to NOT install on the System Disk, but instead on another partition, say, the D drive, then rather than changing the default location every time, you can edit the registry as follows:

Now open Regedit and navigate to the following key:

Now in the right pane look for the value ProgramFilesDir and/or ProgramFilesDir (x86) depending on whether your Windows is 32-bit or 64-bit.

Double-click on it and in the box which opens up change its Value data from C:\Program Files to say, D:\Program Files.

The default directory for the installation of all your programs shall now be D:\Program Files.

If you are using Windows 64-bit, you have to change the value of ProgramFilesDir and ProgramFilesDir (x86).

How to Change Program Files Location in Windows 10, 8, 7

  1. Download Restoro PC Repair Tool that comes with Patented Technologies (patent available here).
  2. Click Start Scan to find Windows issues that could be causing PC problems.
  3. Click Repair All to fix issues affecting your computer’s security and performance
  • Restoro has been downloaded by 0 readers this month.

Normally if you have Windows 8, Windows 10 or any other version of Windows operating systems, you will definitely have your program files location in your “C:/” driver where the operating system itself is usually installed. This is mainly because the system needs to ensure a good correlation between the programs that you are installing and the Windows 8 or Windows 10 operating system.

Of course you can change this location anytime and we will see how to do so by reading the tutorial posted a few rows below. But first of all, we will need to know the consequences that may happen if we change the program files location. Mainly the program files folder is put there for a good reason, if you move it and all your programs will be moved to another location you may experience some system errors after a while.

Читайте также:  Загрузить linux mint wizard livecd usb

Change program files directory on Windows 10, 8, 7

  1. While on your Desktop in Windows 8, Windows 10 or Windows 7, you will need to press and hold the buttons “Windows” and “R”.
  2. Holding the buttons above will open the “Run” window where we will need to type “Regedit”.
  3. After typing “Regedit” you will need to press the “Enter” button on the keyboard.
  4. Now you should have the “Registry Editor” window in front of you.
  5. On the left side of the window left click on the “HKEY_LOCAL_MACHINE” folder.
  6. In the “HKEY_LOCAL_MACHINE” folder left click on the “ SOFTWARE” folder.
  7. In the “SOFTWARE” folder left click on the “Microsoft” folder.
  8. In the “Microsoft” folder left click on the “Windows” folder.
  9. And now in the “Windows” folder left click on the “CurrentVersion” folder.
  10. Now that you are in the “CurrentVersion” folder you will have to look in the right side of the window for a “ProgramFilesDir” item. Note: if you have a 64 bit system it will be a “ProgramFilesDir (x86)” item.
  11. Double click (left click) on it and from there you will be able to change the path of the “Program files” folder by entering a new path in the “Value data” section of the window.
  12. After you are done selecting a path you will need to left click on “OK” and then close the “Registry Editor” window.
  13. If the changes did not work after you closed the window try a reboot of the Windows 8 or Windows 10 system and try it afterwards.

Now, you know how to change the path of the program files folder and you can see that it didn’t took up much of your time. Always keep in mind that if you change the path of the program files folder, this may cause malfunctions in the system. Microsoft made it clear that it does not support changing the location of the program files:

Microsoft does not support changing the location of the Program Files folder by modifying the ProgramFilesDir registry value. If you change the location of the Program Files folder, you may experience problems with some Microsoft programs or with some software updates.

RELATED STORIES TO CHECK OUT:

Оцените статью