【问题标题】:Get-ChildItem return access denied error when run as "SYSTEM"以“SYSTEM”身份运行时,Get-ChildItem 返回访问被拒绝错误
【发布时间】:2021-09-24 13:29:52
【问题描述】:

我正在尝试创建一个脚本以通过网络获取文件夹的内容。我注意到 Get-Childitem 在列表中的每个其他 IP 地址上都会抛出“拒绝访问”错误。

例如我这样列出IP:

  • IP1
  • IP2
  • IP3
  • IP4

Get-ChildItem 适用于 IP1 和 IP3,但返回 IP2 和 IP4 的访问被拒绝错误。仅当我在以 SYSTEM 身份运行的控制台上运行脚本时才会发生这种情况。 编辑:我创建此脚本的远程工具只能作为系统运行控制台

谁能告诉我代码中是否有任何可能导致此问题的内容?

#Set Variables
$pw = Read-Host -AsSecureString "Enter password"
$usrname = 'username'
$folderpath = 'C$\Folder\Subfolder1\Subfolder'

#Loop
foreach ($ipaddress in Get-Content -Path .\DeviceIPList.txt) {
$credential = New-Object System.Management.Automation.PsCredential("$ipaddress\$usrname",$pw)
    Try {
        if ($(Test-Path drv:) -eq 'True') {
            Remove-PSDrive "drv"
        } else { 
            New-PSDrive -Name "drv" -PSProvider FileSystem -Root "\\$ipaddress\C$" -Credential $credential -ErrorAction Stop | Out-Null
        } 
        $vhdfile = Get-ChildItem -path "\\$ipaddress\$folderpath" -ErrorAction Stop    
        Write-Host -ForegroundColor Green "$ipaddress,Found $vhdfile in $($folderpath.Replace('$',':'))"
        Write-Output "$ipaddress,Found $vhdfile in $($folderpath.Replace('$',':'))" | Out-File -Append .\Report.txt
        }
    Catch [System.ComponentModel.Win32Exception] {
        Write-Host -ForegroundColor Cyan "$ipaddress,$_"
        Write-Output "$ipaddress,$_" | Out-File -Append .\Report.txt
        }
    Catch {
        Write-Host -ForegroundColor Yellow "$ipaddress,$_"
        Write-Output "$ipaddress,$_" | Out-File -Append .\Report.txt
        }
    Finally {
        $error.Clear()
        Start-Sleep -Seconds 2
        net use \\$ipaddress\$folderpath /d 2>&1>$null
        }
}
    

【问题讨论】:

  • 系统账号用于本地系统,一般不能使用系统账号连接远程机器。
  • 抱歉,我已更新帖子以进行澄清。不幸的是,我使用的工具只能将控制台作为系统运行。有没有办法让它工作?

标签: powershell get-childitem


【解决方案1】:

如果drv: 存在,您在此处的if 语句将删除它,不会创建新驱动器。尝试将New-PSDrive移到Else之外:

if ($(Test-Path drv:) -eq 'True') {
  Remove-PSDrive "drv"
} 
New-PSDrive -Name "drv" -PSProvider FileSystem -Root "\\$ipaddress\C$" -Credential $credential -ErrorAction Stop | Out-Null

这是一个问题,因为您在 Get-ChildItem 中使用了整个 \\$ip\c$\ unc。如果drv: 被删除,那么您将要求Get-ChildItem 以当前用户身份连接,这将无法作为system 工作。这也可能是您可以每隔其他时间连接的原因。

使用drv: 应该通过抛出“drv: 不存在”之类的错误来告诉您这是否是问题:

$folderpath = 'Folder\Subfolder1\Subfolder'
$vhdfile = Get-ChildItem -path "drv:\$folderpath" -ErrorAction Stop

可能是 SYSTEM 无法使用 net use /d 删除 PSDrive - 它可能会引发错误,但您已将其输出设为空。请尝试在此处再次使用Remove-PSDrive

Finally {
  $error.Clear()
  Start-Sleep -Seconds 2
  Remove-PSDrive "drv"
}

作为系统运行很好,因为您向 New-PSDrive 提供了不同的凭据。

【讨论】:

  • 成功了!我将 new-psdrive 移出 else 并按照您的建议更改子项的路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多