PS Beginner: ForEach Set-ADUser

Hi Everyone,

i just started using PowerShell and want to do the following:

$Feldname = Read-Host

Write-Host `n`n
Write-Host "Show only users, where '$Feldname' is emtpy."
Write-Host `n

Get-ADUser -Filter * -properties * | Where-Object {$PSItem.$Feldname -eq $null} | ft Name, SamAccountName, OfficePhone, department, company | foreach ($User in $PSItem){
  Set-ADUser -identity $user -Company "TEST Company" 

Get-ADUser -Filter * -properties * | Where-Object {$PSItem.$Feldname -eq "LM IT Services AG"} | ft Name, SamAccountName, OfficePhone, department, company

When i execute the script without Foreach i will be prompted to enter an AD Attribute, e.g. “Company”. Then the result shows only users, who have no Company set.
Now i want to set the Company Attribute to a fixed value.
Sadly this isn’t working and i don’t know why.

It would be awesome if you could help me out of this. :slight_smile:


Patrick, welcome to

Format cmdlets like Format-Table should be the very last cmdlet in a pipeline and they break the pipeline. They are just to produce nice output on the screen. It’s actually impossible (or nonsense) to pipe the output of these cmdlets to the next cmdlet.
Regardless of that: there is a destinct difference between the Foreach-Object cmdlet which has the alias Foreach and the statement Foreach. I guess you’ve mistaken this in your code.

As Olaf says the format table have no use in the statement that leads to the Set-Aduser statement.

Also in regard to the foreach the syntax is incorrect.

E.g. the following should work.
$users = Get-ADUser -Filter * -properties * | Where-Object {$PSItem.$Feldname -eq $null}

foreach ($user in $users){
Set-ADUser -identity $user.SamAccountName -Company “TEST Company”

Or if using your example.

Get-ADUser -Filter * -properties * | Where-Object {$PSItem.$Feldname -eq $null} | foreach {
Set-ADUser -identity $_.SamAccountName -Company “TEST Company”

You should also see that there are errors in the syntax if you’re using e.g. Powershell ISE or similar editor to write the script.
Since you’ll get red “squiggly” lines after the foreach.

Also, as a best practice when looking up things against the AD is not to use -filter * and -properties *.
If it’s a large AD you’re working against that means “all users” + “all properties”.
Which can be quite a lot of data to pull if you only need a small subset of properties.

Hope this example helps. Filtering for null properties is a little weird.

get-aduser -ResultSetSize 25 -filter “-not Organization -eq ‘*’” |
set-aduser -Organization -whatif