if loop not processing correctly within foreach, why??

by tommls at 2013-02-08 09:39:49

I have this code:


[CmdletBinding()]
param(
[parameter(mandatory=$true)][string]$UserID
)
cls
$servers = @(‘x5’,‘x6’,‘x7’,‘x8’)
foreach ($server in $servers) {
If(-Not(Test-Path “\$erver\C$\Users\$UserID\AppData\Local\Temp&quot;)) { # if true exit for, process the NEXT server<br> &quot;\\$server\C$\Users$UserID\AppData\Local\Temp does not exist”
Continue}
Set-Location “\$server\C$\Users\$UserID\AppData\Local\Temp&quot;<br> if (-not (Test-Path &quot;Low&quot;)) {<br> New-Item -Path &quot;Low&quot; -ItemType &quot;Directory&quot; -ErrorAction SilentlyContinue<br> }<br> icacls&#46;exe &quot;\\$server\C$\Users$UserID\AppData\Local\Temp\Low” /setintegritylevel (OI)(CI)low
}


The If NOT statement always causes the for loop to return the ‘does not exist’ statement even on a user (ME) where I know the desired directory exists. Why?? How do I fix this?? Should I use foreach-object???

Thank you, Tom
by ArtB0514 at 2013-02-08 10:42:51
You are missing the “s” in $server in your first IF statement. The resulting path has a null value for the server, which will make it always return the “does not exist” result.
by tommls at 2013-02-08 11:14:47
OHHHHHHHHHHHHHHHHHH THANK YOU…!!
I never would have caught that in 1,344,344 years…!!
Fixed and the script works perfectly :slight_smile:
Thank you, Tom
by ArtB0514 at 2013-02-08 12:00:07
No problem, I need the same kind of help often enough myself. But I do have a bit more experience with this kind of error and would have found it without help a little bit quicker, about PI/3 million years!