Windows shell folders personal

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

Читайте также:  Определить жесткие диски linux

Эта команда создает папку 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 folders personal

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

On ca. 20 of more than 1000 computers, we suddenly had weird issues, such as being unable to install programs or rename folders. I found that these issues were caused by invalid paths for shell folders in Registry.

Under HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer, the following entries were corrupt on these machines:

Shell Folders\Personal was «C:\User», «C:\Users» or «C:\Users\» (should be «C:\Users\username\Documents»)

Shell Folders\My Pictures was «C:\User», «C:\Users» or «C:\Users\» (should be «C:\Users\username\Pictures»)

User Shell Folders\Personal was «%USER», type REG_SZ (should be «%USERPROFILE%\Documents», type REG_EXPAND_SZ)

User Shell Folders\My Pictures was «%USER», type REG_SZ (should be «%USERPROFILE%\Pictures», type REG_EXPAND_SZ)

All other entries (My Music, Desktop etc.) were fine. The problem sometimes seems to reappear after it was fixed, but I could not trace that so far. (On some machines I keep monitoring these keys.)

Читайте также:  Не работает удаленное аудио windows 10

For the moment I wrote a logon script to fix the keys . but I really would like to know what might be the root cause. Of course I examined some of the affected machines with various Malware scanners, but nothing was found.

Has anyone else had a similar experience, or does someone know what might cause the issue? SCCM? Forefront? Flash? A Windows update?

BTW, this is the fixing script:

Answers

Yes, let’s enable Audit and see if any process did the change. Please also enlarge Security Event to ensure it won’t be overwritten frequently.

Click Start, click Run, type eventvwr and press OK.
Right-click Security in the left panel and click OK.
Set the Maximum log size to 200000KB. Click OK.

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

We actually found the reason in a custom script. Under certain conditions this caused the corrupted entries.

So, it was something specific to our company.

All replies

The issue might be caused by the redirect folder on your domain. When you redirect special folders to another location, the User Shell Folder registry path is modified accordingly.

Please try this KB to check if it can solve your issue:

Since the issue occur with large amount of machines, I suggest to contact Server Forum to check if any GPO or other domain configuration has problem:

The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.

TechNet Community Support

Thanks, but that does not apply to us. We had it on approx. 50 of few thousand machines, but these machines and their users are in same OUs as other machines that do not have the problem. We also do not have any GPOs that could cause such, especially as all these computers and users (affected and non-affected) do have the same GPOs applied, and were imaged from the same MDT image and have the same hardware, drivers and software.

I personally think that it is some application software causing it . but seems like we are the only ones having this. Weird.

Try to remove all necessary software and logon with Clean Boot to check if the same issue occurs.

And please check if these machine set folder redirection to server. If the issue persists, I suggest to leave the domain and let PC work alone to check if the issue related with Windows 7 itself.

TechNet Community Support

Since the issue occur every few weeks, and your workaround is a domain environment, we need to narrow down the issue is Windows7 itself or the domain problem.

Thus let Windows 7 work alone is an option to troubleshoot the issue.

TechNet Community Support

Well, my original question was not aimed at getting advice how to narrow down the issue, especially since it occurs unregularly. We have 3400 domain machines where the issue does not appear, so of what use will it be to add a single non-domain machine. (Besides, the users could not work when their machine is not joined to the domain, so how should they test it?)

My original question was this:

Has anyone else had a similar experience, or does someone know what might cause the issue? SCCM? Forefront? Flash? A Windows update?

So, if no one «else had a similar experience», I’ll have to investigate it myself further. I was hoping for someone with the same issue, but obviously there is no one here.

I am trying to involve someone familiar with this topic to further look at this issue.

TechNet Community Support

Well, I seem to have a similar issue.

In a domain there is one user (known so far) who has reported an issue where she would change her TS desktop, only to find out that the changes applied to her local desktop as well.

In AD, both «Profile» and «Terminal Services Profile» point to different «personal» locations.
In the registry key «. \shell folders» all other maps (i.e. documents, pictures, etc..) point the correct locations, except for Desktop, which point to a general location.

PC Registry («. \shell folders»)
Desktop : \\server3\ts-desktop
Documents : c:\documents and settings\username\documents
Pictures : c:\documents and settings\username\pictures
etc. etc.

The domain group policy has not been configured to re-direct folders. And, as far as I can see, there’s no policy that applies to just this one user.
The user reported the same issues when logging onto other PC’s.

I will investigate further on this issue. But have to admit I am out of ideas for the moment.

Читайте также:  Windows 10 как удалить известные сети

EDIT: Needless to say my user is working on an XP machine. So perhaps this isn’t the right thread for my post.
But I don’t think is OS-related.

I was involved to check this issue.

Based on my knowledge and experience, most of the actions will be recorded in the Event logs, for the folder redirection related issue, the event would be logged in Application event logs, the event Source would be like «Folder Redirection». We can check if there are any related events. Since the issue will reappear, I think the actions will be recorded in the event logs. This would be one of the clues to find the cause.

When this issue occurs again next time, please run «rsop.msc» on the problematic machine, then check the settings. Just to ensure that no related policies are enabled.

If this issue can be always reproduced, we can enable the boot logging process monitor(Options — Enable Boot Logging), then reproduce the issue. After we reboot the server, save the log data, then search the key words(such as «C:\users») in the logs. This log usually logs the boot process and will give us some clues.
Process monitor can be downloaded here:
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx

Thanks
Zero
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

Svhelden, you are not using TSProfile, Roaming Profile, Folder Redirection right?

As the issue is abnormal and cannot be reproduced, based on my experience, we could check the following path in reg:

I notice that what you check is HKCU

When you run as Administrator, the administrator is considered as the «Current User» and thus the «HKEY_CURRENT_USER» is indeed pointing to administrator’s profile. In other words, the HKEY_CURRENT_USER branch you saw is NOT the affected user’s profile. So we need to check the affected profile path:

Please go to HKEY_USERS to locate that user and then check:
HKEY_USERS\GUID\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
HKEY_USERS\GUID\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

If the issue persists, we need to enable Audit to catch the exact process.

Be frankly, I agree with Leo’s suggestion. If it is possible, we could sacrifice one client and disjoin the domain, see how it works then.

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

When you run as Administrator, the administrator is considered as the «Current User» and thus the «HKEY_CURRENT_USER» is indeed pointing to administrator’s profile. In other words, the HKEY_CURRENT_USER branch you saw is NOT the affected user’s profile.

Well . I am an administrator myself, and I had the issue. So, for me of course HKCU is HKCU. And as for the other users, of course I checked their HKU\ branch, NOT my own HKU.

Be frankly, I agree with Leo’s suggestion. If it is possible, we could sacrifice one client and disjoin the domain, see how it works then.

I do not agree, because there is a 99 % chance that it will not happen on this machine again, regardless whether we remove it from the domain or not.

This kind of issues mostly occur when Folder Redirection is configured. As it doesn’t exist, whether or not the reg always points to a same invalid path: on each problematic clients, User Shell Folders\My Pictures are pointed to «%USER»?

If you’d like to dig it further, we can enable Audit on these registry and we’ll be able to know the «Criminal» when the issue happens.

1. Enable audit policy named “Audit object access”.
1) Please Log on to affected computer as admin account, and run the Gpedit.msc to open the Group Policy Editor.
2) Please click the following items to open Computer Configuration, Windows Settings, Security Settings, Local Policies, Audit Policy.
3) In the right panel, please double click Audit object access to open the Audit object access properties.
4) Please select the Define these policy settings check box, and select the Success check box.

2. Set the SACL on the registry of these values.
1) Navigate to

HKEY_USERS\GUID\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
HKEY_USERS\GUID\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

2) Right click Shell Folders/User Shell Folders and click Permission.
3) Click Advance tab, click Auditing tab, click Add, and select the group Everyone.
4) In pop-up, set following operations under the Successful menu. (Set Value, Create Subkey and Delete)

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

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