Щоб вирішити проблему з помилками доступу при виконанні команди Get-ChildItem, потрібно надати процесу PowerShell необхідні привілеї для доступу до системних каталогів, таких як C:\Windows\CSC та C:\Windows\System32\LogFiles\WMI\RtBackup.
Варіант 1 (Магічна команда):
Необхідно ввімкнути привілей SeBackupPrivilege для поточного процесу PowerShell. Цей привілей дозволяє обхід перевірки дозволів на читання файлів та каталогів.
Ось як це можна зробити:
- Створіть функцію
Enable-Privilege у вашій сесії PowerShell:
function Enable-Privilege {
param(
[ValidateSet(
"SeAssignPrimaryTokenPrivilege","SeAuditPrivilege","SeBackupPrivilege","SeChangeNotifyPrivilege",
"SeCreateGlobalPrivilege","SeCreatePagefilePrivilege","SeCreatePermanentPrivilege","SeCreateSymbolicLinkPrivilege",
"SeCreateTokenPrivilege","SeDebugPrivilege","SeEnableDelegationPrivilege","SeImpersonatePrivilege",
"SeIncreaseBasePriorityPrivilege","SeIncreaseQuotaPrivilege","SeIncreaseWorkingSetPrivilege","SeLoadDriverPrivilege",
"SeLockMemoryPrivilege","SeMachineAccountPrivilege","SeManageVolumePrivilege","SeProfileSingleProcessPrivilege",
"SeRelabelPrivilege","SeRemoteShutdownPrivilege","SeRestorePrivilege","SeSecurityPrivilege","SeShutdownPrivilege",
"SeSyncAgentPrivilege","SeSystemEnvironmentPrivilege","SeSystemProfilePrivilege","SeSystemtimePrivilege",
"SeTakeOwnershipPrivilege","SeTcbPrivilege","SeTimeZonePrivilege","SeTrustedCredManAccessPrivilege","SeUndockPrivilege"),
Parameter(Mandatory = $true)]
[string]$Privilege,
[System.Diagnostics.Process] $Process = $null,
[Switch] $Disable
)
$definition = @'
using System;
using System.Runtime.InteropServices;
public class AdjPriv
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LUID {
public int LowPart;
public int HighPart;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LUID_AND_ATTRIBUTES {
public LUID Luid;
public int Attributes;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct TOKEN_PRIVILEGES {
public int PrivilegeCount;
public LUID_AND_ATTRIBUTES Privileges;
}
public const int SE_PRIVILEGE_ENABLED = 0x00000002;
public const int SE_PRIVILEGE_DISABLED = 0x00000000;
public const int TOKEN_QUERY = 0x00000008;
public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public const string ADVAPI32 = "advapi32.dll";
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, out IntPtr TokenHandle);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
}
'@
$processHandle = if ($Process) { $Process.Handle } else { (Get-Process -Id $PID).Handle }
Add-Type $definition
$ptr = [IntPtr]::Zero
$result = [AdjPriv]::OpenProcessToken($processHandle, [AdjPriv]::TOKEN_ADJUST_PRIVILEGES -bor [AdjPriv]::TOKEN_QUERY, [ref] $ptr)
if (!$result) {
Throw "Error in OpenProcessToken"
}
$tp = New-Object AdjPriv+TOKEN_PRIVILEGES
$luid = New-Object AdjPriv+LUID
$result = [AdjPriv]::LookupPrivilegeValue($null, $Privilege, [ref] $luid)
if (!$result) {
Throw "Error in LookupPrivilegeValue"
}
$tp.PrivilegeCount = 1
$tp.Privileges = New-Object AdjPriv+LUID_AND_ATTRIBUTES
$tp.Privileges.Luid = $luid
if ($Disable) {
$tp.Privileges.Attributes = [AdjPriv]::SE_PRIVILEGE_DISABLED
} else {
$tp.Privileges.Attributes = [AdjPriv]::SE_PRIVILEGE_ENABLED
}
$result = [AdjPriv]::AdjustTokenPrivileges($ptr, $false, [ref] $tp, 0, [IntPtr]::Zero, [IntPtr]::Zero)
if (!$result) {
Throw "Error in AdjustTokenPrivileges"
}
}
- Після визначення функції, увімкніть привілей
SeBackupPrivilege:
Enable-Privilege SeBackupPrivilege
- Тепер виконайте вашу початкову команду
Get-ChildItem:
Get-ChildItem -Path 'C:\Windows' -Filter *.jpg -File -Recurse |
Where-Object { $_.DirectoryName -ne 'C:\Windows' } |
Where-Object { $_.Length -gt 2MB } |
Select-Object Name, Length, CreationTime, Attributes |
Sort-Object Name |
Tee-Object -FilePath 'D:\Университет\СПЗ\ЛБ1\output.txt' -Append
Це дозволить PowerShell отримати доступ до всіх файлів та каталогів, необхідних для виконання вашої команди, без помилок "Отказано в доступе".
Варіант 2 (Налаштування параметрів):
Якщо ви не хочете змінювати привілеї, можна налаштувати команду Get-ChildItem таким чином, щоб вона обходила каталоги з обмеженим доступом.
Наприклад, ви можете виключити проблемні каталоги з сканування:
$excludeDirs = @('CSC', 'System32\LogFiles\WMI\RtBackup')
Get-ChildItem -Path 'C:\Windows' -Filter *.jpg -File -Recurse -Directory |
Where-Object { $excludeDirs -notcontains $_.PSChildName } |
ForEach-Object {
Get-ChildItem -Path $_.FullName -Filter *.jpg -File |
Where-Object { $_.DirectoryName -ne 'C:\Windows' -and $_.Length -gt 2MB } |
Select-Object Name, Length, CreationTime, Attributes
} |
Sort-Object Name |
Tee-Object -FilePath 'D:\Университет\СПЗ\ЛБ1\output.txt' -Append
Цей підхід виключає зазначені каталоги та запобігає появі помилок доступу.
Висновок:
Рекомендується використовувати перший варіант з увімкненням привілею SeBackupPrivilege, оскільки він надає необхідні права доступу для повного виконання команди без помилок.
Команда для найвищого доступу:
Enable-Privilege SeBackupPrivilege