Populate Checkedlistbox with Servers - powershell

I am trying to populate a list with the servers in my domain, and i have partial success. There are 5 items in my list, which is as many servers as i have.
Unfortunately they are all just called [Collection]
Form is generated with Sapien Powershell Studio
$strCategory = "computer"
$strOperatingSystem = "Windows*Server*"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("OperatingSystem=$strOperatingSystem")
$colProplist = "name"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) }
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults)
{
$objComputer = $objResult.Properties;
$objComputer.name
$checkedlistbox1.Items.add($objComputer.name)
}
What can I do to have the proper name show up in the checkedlist.
Thanks for any assistance :)

The result object from DirectorySearcher.FindAll() method contains a special property named Properties that returns a typed collection containing the values of properties of the object found in the AD.
This means that you can simply do
. . .
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults) {
$checkedlistbox1.Items.add($objResult.Properties['name'][0])
}

I suggest you use Get-ADComputer instead to get the list of your servers.
The you just loop thrue the list and add the servername to your checkedlist
$Servers= Get-ADComputer -Filter {OperatingSystem -Like 'Windows *Server*'} #-Property * #the property flag is not needed if you just want the Name (see comment from Theo)
foreach ($srv in $Servers) {
#Unmark to debug
#$srv.Name
#$srv.OperatingSystem
$checkedlistbox1.Items.add($srv.Name)
}

Related

PowerShell Script to get login details

Hi I have written the following code to get the login user details, but I'm getting only the system name. I also need the username along with it. Please help. Thanks in advance.
function GetList
{ param ([string]$base)
$blah = [ADSI]"$base"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = "(objectClass=Computer)"
$objSearcher.SearchRoot = $blah
$PropList = "cn","operatingsystem"
foreach ($i in $PropList){$objSearcher.PropertiesToLoad.Add($i)}
$Results = $objSearcher.FindAll()
foreach ($objResult in $Results)
{
$OS = $objResult.Properties.operatingsystem
If ($OS -match "Windows")
{
Echo $objResult.Properties.cn
}
}
}
Maybe $env:USERNAME is thing you are searching for. There is also $env:UserDomain and $env:ComputerName.

Directory Search to array to populate Windows form datagrid

I'm creating a windows form via Powershell where users can search for the computers registered to a person, or search for a person's registered computers. The registered user is stored in the description field, the computer names in the name field. $SearchIn holds the value to search for, $field indicates the field to search in.
I can get the results I want via the console, but I'm attempting to push the results into a datagrid view on a windows form. The datagrid in the script below is called $dataGrid1. What I have below is an attempt to push the directory services search to an array, then set the datagrid datasource to an array. I thought because the $objectComputer is an object rather than an array I had to create an array using New-Object System.Collections.ArrayList and populate it using the addrange method set to the $objComputer object.
Ultimately what I get no matter what I'm trying is a blank datagrid view. Can someone point me in the right direction?
Function Get-Info
{
param($SearchIn,$Field)
if ($field -eq "Name"){
$filter="name=*$SearchIn*"
}
else
{
$filter="description=*$SearchIn*"
}
$strCategory = “computer”
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = $filter
$colResults = $objSearcher.FindAll()
$objComputer=#()
foreach ($objResult in $colResults)
{
$objComputer+=($objResult.Properties.item("Name"), $objResult.Properties.item("Description"))}
$array=New-Object System.Collections.ArrayList($null)
$array=.addrange($objComputer)
$dataGrid1.DataSource = $array
$fComputerSearch.refresh()
}#End Get-Info
Uff your code is rather hard to read, next time please check the brackets {}
I think the end is incorrect:
$array=New-Object System.Collections.ArrayList($null)
$array=.addrange($objComputer)
$dataGrid1.DataSource = $array
$fComputerSearch.refresh()
I think it should be something like this:
# the fastest way to create empty ArrayList
[System.Collections.ArrayList]$list = #()
$list.AddRange($objComputer)
$dataGridView = New-Object System.Windows.Forms.DataGridView -Property #{
Size=New-Object System.Drawing.Size(1024,768)
ColumnHeadersVisible = $true
DataSource = $list
}
$form.Controls.Add($dataGridView)
$form.ShowDialog()

Powershell DirectorySearcher Null Output

I'm writing a powershell script that searches for users inside an Active Directory OU and allows me to reset passwords by choosing matches from a list. I found a Tutorial that uses the System.DirectoryServices.DirectoryEntry and System.DirectoryServices.DirectorySearcher, and modified it like so:
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP:\\[REDACTED]")
##ReadSTDIN
$strSearch = Read-Host -Prompt "Search"
$strCat = "(&(objectCategory=User)(Name=*" + $strSearch + "*))"
## Search Object
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strCat
$objSearcher.SearchScope = "Subtree"
#Load Required Properties into the dynObjLink
$objSearcher.PropertiesToLoad.Add("name")
$objSearcher.PropertiesToLoad.Add("userPrincipalName")
$objSearcher.PropertiesToLoad.Add("SamAccountName")
##Magical Search Function
$colResults = $objSearcher.FindAll()
$colResults.PropertiesLoaded
#for every returned userID add them to a table
ForEach ($objResult in $colResults)
{$a++
$objResult.count
$objItem = $objResult.Properties
$objItem.name
$objItem.userPrincipalName
$results.Add($a, $objItem.name + $objItem.userPrincipalName + $objItem.SamAccountName)
}
#Print Table
$results | Format-Table -AutoSize
This works well enough, but when it prints data I can only get the "first name" value of anything that comes back. Everything else becomes NULL and I can't figure out why.
Name Value
---- -----
3 {James3 [REDACTED], $null, $null}
2 {James2 [REDACTED], $null, $null}
1 {James1 [REDACTED], $null, $null}
I've tried different kinds of authentication and manipulating values, but the DirectorySearcher object only seems to collect the "name" value of any record it returns, no matter what I load into it. Help?
Here's a bit shorter (and PowerShell v2-compatible) way of doing this:
#requires -version 2
param(
[Parameter(Mandatory=$true)]
[String] $SearchPattern
)
$searcher = [ADSISearcher] "(&(objectClass=user)(name=$SearchPattern))"
$searcher.PageSize = 1000
$searcher.PropertiesToLoad.AddRange(#("name","samAccountName","userPrincipalName"))
$searchResults = $searcher.FindAll()
if ( $searchResults.Count -gt 0 ) {
foreach ( $searchResult in $searchResults ) {
$properties = $searchResult.Properties
$searchResult | Select-Object `
#{Name = "name"; Expression = {$properties["name"][0]}},
#{Name = "sAMAccountName"; Expression = {$properties["samaccountname"][0]}},
#{Name = "userPrincipalName"; Expression = {$properties["userprincipalname"][0]}}
}
}
$searchResults.Dispose()
Note that there's no need to build a list and output afterwards. Just output each search result. Put this code in a script file and call it:
PS C:\Scripts> .\Searcher.ps1 "*dyer*"
If you omit the parameter, PowerShell will prompt you for it (because the parameter is marked as mandatory).
try using Properties matching to the PropertiesToLoad
$entry = new-object -typename system.directoryservices.directoryentry -ArgumentList $LDAPServer, "ldap", "esildap"
$entry.Path="LDAP://OU=childOU,OU=parentOU,DC=dc1,DC=dc2"
$searcher = new-object -typename system.directoryservices.directorysearcher -ArgumentList $entry
$searcher.PropertiesToLoad.Add('samaccountname')
$searcher.PropertiesToLoad.Add('mail')
$searcher.PropertiesToLoad.Add('displayname')
$objs = $searcher.findall()
foreach($data in $objs)
{
$samaccountname = $data.properties['samaccountname'][0] + ''
$mail = $data.properties['mail'][0] + ''
$displayname = $data.properties['displayname'][0] + ''
}
when accessing the properties of the resultset you get a System.DirectoryServices.ResultPropertyValueCollection type for each property
to get a string value for passing to a database the property value access the zero index of the object

Some computers on a powershell GPO script not recognizing parameter

I am running into an issue where about 10% of computers on my network are throwing a very strange errors when processing. The error I get is "Where-Object : A Parameter cannot be found that matches paramter name 'Property'" the code I'm using is as follows.
#Create ADSI Search object to query Active Directory for usernames
#Start-Transcript -Path "$env:userprofile\Desktop\log.txt"
$strFilter = "objectCategory=user"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=SD25;DC=DC;DC=DC")
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 100000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
#Populate ADSI with the extra fields of samaccountname which is the username, and memberof which gives you roughly which groups they are a memberof
$colProplist = "samaccountname", "memberof"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
#Run the Search
$colResults = $objSearcher.FindAll()
#$colResults
$resultsarray = #()
#The way ADSI returns results, it populates all an array of every username listed within the scope, I then use this foreach recursive loop to find the name I need
foreach ($objResult in $colResults)
{
#Here I am taking each of the users, and finding the one which has the samaccountname of the user that is currently logged in
$objItem = $objResult.Properties | Where-Object -Property memberof -like ALL
#$groups = $objItem.memberof
#This is for diagnostics, if you output a logfile it will tell you the name and groups it is a member of
$objitem
}
#This is the beginnings of searching for a computer container in active directory.
$compFilter = "objectCategory=computer"
$compDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=OU;DC=DC;DC=DC")
$compSearcher = New-Object System.DirectoryServices.DirectorySearcher
$compSearcher.SearchRoot = $objDomain
$compSearcher.PageSize = 100000
$compSearcher.Filter = $strFilter
$compSearcher.SearchScope = "Subtree"
$compProplist = "name"
foreach ($i in $compPropList){$compSearcher.PropertiesToLoad.Add($i)}
$compResults = $compSearcher.FindAll()
foreach ($compR in $compResults)
{
}
#Stop-Transcript
IIRC -Property was introduced to Where-Object with PowerShell 3.0. Could you script be running on PowerShell 2.0?
Responding to comment
You need to create a filter script in the form of a scriptblock (i.e. PowerShell code in a set of braces) instead of using the comparison operator parameters they added for 3.0.
Try using
Where-Object { $_.memberof -like "ALL" }
or something like that. $_ refers to the current object in the pipeline. I couldn't find the docs for version 2.0 but I found Using the Where-Object Cmdlet for version 1.0 which was relevant for 2.0 AFAIK and should help you.

Filtering Powershell output

I am trying to filter the output of the following PS script;
We use server names like:
SRV-APP-001,
PRD-APP-001,
TST-APP-001
etc...
$strCategory = "computer"
$strOperatingSystem = "Windows*Server*"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("OperatingSystem=$strOperatingSystem")
$colProplist = "name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults)
{
$objComputer = $objResult.Properties;
$objComputer.name
}
The output of this script are all the servers in the Domain.
But I want only see the servers that start with "SRV" or "PRD"
the | where { $_name -like "SRV*"} is not realy working after the $objComputer.name part.
Thank you in advance
Change the filter to:
"(|(name=SRV*)(name=PRD*))(OperatingSystem=Windows*Server*)"