Home > front end >  Adding a Custom Expression in a Select array of Computers in AD
Adding a Custom Expression in a Select array of Computers in AD

Time:09-06

I am trying to add a custom field in an array of computers searched for in AD.

This Variable has a list of computers that contains name and Description $Computers

I want to create a custom field called 'newdescript' with the values as follows: Date moved from, and the computers DistinguishedName.
Like so:

$newDescript = "$(Get-Date) moved from $($Computer.DistinguishedName)"

Should appear like:

09/05/2022 11:16:18 moved from CN=PCNAME,OU=Some OU,DC=mydomain,DC=com

The code:

##New field at the end.  
$Computers | Select-Object Name, Description, newDescript

##newDescript must be = $newDescript  

Output currently:

Name            Description           newDescript
----            -----------           -----------
PCNAME          Old Description       {}  

Output should be:

Name            Description           newDescript
----            -----------           -----------
PCNAME          Old Description       09/05/2022 11:16:18 moved from CN=PCNAME,OU=Some OU,DC=mydomain,DC=com

Once I have the correct format I can then export it to csv.

CodePudding user response:

You can use the following calculated property to get the desired output:

$Computers | Select-Object Name, Description, @{
    N = 'newDescript'
    E = { "$((Get-Date).ToString('dd/MM/yyyy HH:mm:ss')) moved from $($_.DistinguishedName)" }
}

The use of Select-Object is not mandatory for this, it can also be done with a loop creating new PSCustomObjects:

foreach($computer in $Computers) {
    [pscustomobject]@{
        Name        = $computer.Name
        Description = $computer.Description
        newDescript = "$((Get-Date).ToString('dd/MM/yyyy HH:mm:ss')) moved from $($computer.DistinguishedName)"
    }
}
  • Related