Powershell's parallel foreach script block runs in its own runspace so anything defined outside of the block is not visible in it. A few steps to make AD cmdlets work:
- Import activedirectory module within the block. It may throw warning "Error initializing default drive", which can be safely ignored but you will have to
- Specify DC to establish connection via -server parameter in get-ad* cmdlets
get-aduser -server "DC1.foobar.com" -..... - The runspace won't have your credential from main session either so you have to transfer credential explicitly into script block
$cred = get-credential
$users | foreach -parallel {
get-aduser -identity $_.samAccountName -credential $using:cred
} - If there are too many concurrent connections to AD, some connections may fail. Tweak to find the ThrottleLimit that works for you.
- Use inputObject to return result
$_ | add-member -notepropertyname "pn" -notepropertyValue "pv" - Putting it altogether
$cred = get-credential
$users | foreach -parallel {
import-module ActiveDictory
$u=get-aduser -identity $_.samAccountName -credential $using:cred
$_ | add-member -NotePropertyName "DN" -NotePropertyValue $u.distinguishedName
} -ThrottleLimit 5
There are other ways to implement a lock, such as described in Dave's blog, but above file lock works very well and is less complicated.