Jairo Jimenez
Jairo Jimenez

Reputation: 11

Create a String array from an object array in powershell

Im getting the names of these computers and putting them into an array. Now what i want to do is to convert them into a string array to be able to check which policy they are on using a Get-ADComputer for loop or using a foreach loop (Can you recommend which one to use)

$global:arrComputers = @()

    $computerStrings = Get-ADComputer -Filter 'SamAccountName -like "*Name*"' | Select -Expand Name

    foreach ($line in $computerStrings)
    {
        $a = $line.ToString()
        $b = $a.split()

        $temp = @{}
        $temp = New-Object object 
        $temp | Add-Member -MemberType "noteproperty" -Name Name -Value $b[0]

        $global:arrComputers += $temp

    }

    $global:arrComputers

This is the command i want to run to check the policy they are under

Get-ADComputer "Name" -Properties MemberOf | %{if ($_.MemberOf -like "*POLICY_NAME*") {Write-Host "ON"} else {Write-Host "NOT ON"}}

I have tested both blocks of code and they are working the only problem im having is turning that array into a string array. I also tried the ToString() To be able to loop through it with the Get-ADComputer "Name"

Upvotes: 1

Views: 1987

Answers (1)

Iggy Zofrin
Iggy Zofrin

Reputation: 525

"memberOf" property in objects returned by "Get-ADComputer" returns a list of strings containing Distinguished Name of each group this computer is a member of. Therefore, I assume when you say "This is the command i want to run to check the policy they are under", you are referring to a group membership that a group policy is targeting right? Below code then will do it:

$computers = @();
Get-ADComputer -Filter * -Properties Name,MemberOf | %{if ($_.MemberOf -like "*computer_group_name*") { $computers += $_.Name } }

Explanation: First line, define an array $computers Second line, query AD for computer object properties Name,MemberOf then, $_.MemberOf contains group name in string, add Name property(string) to array of strings you defined on line 1

Upvotes: 1

Related Questions