I'm trying to create a script to get content of a folder across the network. I noticed that Get-Childitem throw "Access Denied" error on every other IP addresses in the list.
For example i listed the IP like this:
- IP1
- IP2
- IP3
- IP4
Get-ChildItem worked for IP1 and IP3 but return access denied error for IP2 and IP4. This only happens if I run the script on a console that run as SYSTEM. Edit: The remote tool I create this script for can only run console as system
Can someone tell me if there's anything in the code that might cause this issue?
#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
}
}