get deactivated computers in ad from csv list - powershell

i'm tryin to figure out which computers are deactivated. for that i provide the computer names in a csv list. i just want to output the computers which are deactivated. this is what i have. unfortunately i get all deactivated computers. but i only want that names provided in the csv
Import-CSV -Path "C:\pc_names" | Select -expand Name | Get-ADComputer -searchbase 'XXX' -Filter {(Enabled -eq $False)} -Properties Name, OperatingSystem | Export-CSV “C:\Temp\DisabledComps.CSV” -NoTypeInformation

The problem is likely in the Get-ADComputer command, you specify a SearchBase (assumedly an OU), and a filter for all disabled computers - but never actually include the name of the PC that you piped in from the CSV, so it just returns every disabled PC under that search base.
Try something like this instead;
Import-CSV -Path "C:\pc_names" | Select -Expand Name | Get-ADComputer -SearchBase 'XXX' -Filter {(Enabled -eq $False) -and ($_.Name)} -Properties Name, OperatingSystem | Export-CSV "C:\Temp\DisabledComps.CSV" -NoTypeInformation
Note the $_.Name in the filter.
I've probably got that filter syntax wrong - but that should be the cause.

There is no way you can test if the computername is to be found in an array of names using the -Filter parameter..
You need to first collect computer objects within your SearchBase OU and filter the disabled ones only.
Following that, you filter out the ones that can be found in the $pcNames array using a Where-Object clause:
$pcNames = (Import-Csv -Path "C:\pc_names.csv").Name
Get-ADComputer -SearchBase 'XXX' -Filter "Enabled -eq 'False'" -Properties OperatingSystem |
Where-Object { $pcNames -contains $_.Name } | # or: Where-Object { $_.Name -in $pcNames }
Export-Csv -Path "C:\Temp\DisabledComps.csv" -NoTypeInformation
Note: Get-ADComputer by default already returns these properties: DistinguishedName, DNSHostName, Enabled, Name, ObjectClass, ObjectGUID, SamAccountName, SID, UserPrincipalName. That means you only have to ask for the extra property OperatingSystem in this case

It's pretty obvious that something like this ignores what's piped in and returns many computers.
'comp001' | get-adcomputer -filter 'Enabled -eq $False'
If you wait until the end, there is an error message:
get-adcomputer : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its
properties do not match any of the parameters that take pipeline input.
At line:1 char:13
+ 'comp001' | get-adcomputer -filter 'Enabled -eq $false'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (comp001:String) [Get-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
You can do get-adcomputer inside a foreach loop and test Name as well:
$list = echo comp001 comp002 comp003
$list | % { get-adcomputer -filter 'Enabled -eq $False -and Name -eq $_' }

Related

Getting AD info using Get-ADGroupMember not working as expected

So i am trying to write a script that basically gets a list of AD groups, and then with each group, gets the members and memberof.
So far i have this :
Import-Module ActiveDirectory
$groupList = get-adgroup -filter *| select-object Name | sort-object -property name
Which works fine. nice and simple. No problem. When i run write-output $groupList, it spits out the list of my AD groups. Happy days!
Then I add this :
foreach($group in $groupList){
Get-ADGroupMember -Identity $group
So my code block looks like this :
Import-Module ActiveDirectory
$groupList = get-adgroup -filter *| select-object Name | sort-object -property name
foreach($group in $groupList){
Get-ADGroupMember -Identity $group
}
And get this error :
Get-ADGroupMember : Cannot bind parameter 'Identity'. Cannot create object of type
"Microsoft.ActiveDirectory.Management.ADGroup". The adapter cannot set the value of property "Name".
I have also tried this :
Get-ADGroup -filter * -Properties MemberOf | Where-Object {$_.MemberOf -ne $null} | Select-Object Name,MemberOf
Which works great in Powershell:
Image of working script results
Yet strangley, when i then add the export-csv on the end, that same error returns :
Exported-CSV image
Can someone please educate me, as no doubt its myself being a little stoopid.
Thanks.
$groupList does not directly contain an array of strings / names.
Use the following command to get only the names:
$groupList = Get-ADGroup -Filter * | Sort-Object -Property Name | Select-Object -ExpandProperty Name
MemberOf and Members are arrays. Export-Csv does not know how to export them into a file. Here an example, how to handle this.
Get-ADGroup -Filter * -Properties MemberOf, Members | `
Select-Object -Property Name, #{Name = 'MemberOf'; Expression = {$_.MemberOf -join ';'}}, #{Name = 'Members'; Expression = {$_.Members -join ';'}} | `
Export-Csv -Path 'path' -NoClobber -NoTypeInformation

A script that sends emails via the OUTLOOK SMTP server

I got a task to do a script in PowerShell where I need to get out of AD a list of names that begin with the letter "A" with full name, username and creation date criteria.
 Then export the list with custom headers and export it to a CSV file
Then import the CSV file again and output anyone who works over two years (full name)
So far I have done the script correctly in my opinion because it works.
Now I'm pretty stuck I need to make every user on the list who went out first to make a folder (no matter where) and give full permissions to the folder - I did something but it seems to be incorrect.
Then I need to send an email with a table that states the full name and folder path and that the sender will be no#reply.com.
The code I wrote:
Get-ADUser -filter * -SearchBase "OU=meitavdash,OU=Users,DC=meitav,DC=co,DC=il"
Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} |Format-Table name,SamAccountName,whenCreated
Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} | Select-Object #{n='FullName';e={$_.Name}},#{n='UserName';e={$_.SamaccountName}},#{n='CreateDate';e={$_.WhenCreated}} | export-csv -path c:\userexport.csv
Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} | where {$_.whencreated -le (Get-Date).AddYears(-2)}|Select-Object #{n='FullName';e={$_.Name}}
$sp=$((Get-Date).AddDays(-365*2)); Get-ADUser -Properties whenCreated -Filter {name -like "A*" -and whenCreated -ge $sp}|%{New-Item -Path "c:\temp" -ItemType Directory; icacls "c:\temp" /T /grant "$($_.samaccountname):(OI)(CI)F"
Send-MailMessage is your friend: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-7
As for this...
"my problem I do not know how to actually create a table with the full
name and folder path"
.. is this hat you are after?
Get-ADUser -filter * -SearchBase 'OU=meitavdash,OU=Users,DC=meitav,DC=co,DC=il'
Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} |
Format-Table name,SamAccountName,whenCreated
Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} |
Select-Object #{
n='FullName';e={$_.Name}},
#{n='UserName';e={$_.SamaccountName}},
#{n='CreateDate';e={$_.WhenCreated}} |
export-csv -path c:\userexport.csv
Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} |
where {$_.whencreated -le (Get-Date).AddYears(-2)}|Select-Object #{n='FullName';e={$_.Name}}
$sp=$((Get-Date).AddDays(-365*2))
Get-ADUser -Properties whenCreated -Filter {name -like "A*" -and whenCreated -ge $sp} |
%{
$PathUnc = (New-Item -Path 'c:\temp' -ItemType Directory).FullName
icacls 'c:\temp' /T /grant "$($_.samaccountname):(OI)(CI)F"
}

Import-CSV and Get-ADuser are returning nothing

The command line is returning nothing when I'm using it.
I've already changed Name to DisplayName or CN but this wasn't working too.
Import-Csv "D:\Temp\userExcelRights.txt" |
%{ Get-ADUser -Filter {Name -eq "*$_*"} } |
Select Name,Enabled,SamAccountName,DistinguishedName
The CSV file contains the full name of users.
The -eq operator doesn't support wildcard matches, you need to use the -like operator for that, and you must select a property from the objects that Import-Csv procuces. Also, avoid scriptblock syntax for Get-ADUser filters. Replace
{Name -eq "*$_*"}
with
"Name -like '*$($_.Name)*'"
If the subexpression doesn't work for you, you may need to expand the Name property before feeding it into the loop:
Import-Csv 'D:\Temp\userExcelRights.txt' |
select -Expand Name |
%{ Get-ADUser -Filter "Name -eq '*$_*'" } |
...
With this command it's working:
$data=#(Import-Csv "D:\Temp\userExcelRights.txt").Name
$data | %{ Get-ADUser -Filter "name -like '*$_*'" } |
Select Name,Enabled,SamAccountName,DistinguishedName
Thanks to Ansgar Wiechers.

Powershell script giving an error but runs in shell

I have a requirement to create and update a distribution list for a specific manager and 2 levels down of direct reports. I admit I am not a creative person so I used powershell and did it the best way I could think to do it. The problem is this will be scheduled to run every couple weeks to update the list so it needs to see if a user exists, if not then add him. in the "If" statement to do this I am running into errors when running the script, but if I pull the section of code out and just run manually in powershell it works.
My Execution policy is set to unrestricted so I do not think that is the issue.
We are running Powershell 2 and Unfortunately I can't change that.
Here is my script and the error I am getting.I realize two strings do not match in the lower part of the code, even though they both do the same thing to different files. If I ever get past errors in the first one I should be able to put the same code in both for it to work. Any help would be greatly appreciated.
$Identity="User"
$Listname="Global-Leader"
# This Script will work from a specified Manager and get his direct reports down 2 Levels then #add them to a specified list. This Script works in the AD Module.
# ====================
#| My Company
#| SCRIPT NAME: Leader
#| VERSION: 1
#| VERSION DATE: 3/24/2015
#| AUTHOR: Powershell Rookie
#====================
#load ActiveDirectory module If not already loaded.
if (!(Get-Module -Name ActiveDirectory)) {import-module ActiveDirectory}
Get-AdUser $Identity -properties DirectReports | Select-Object -ExpandProperty DirectReports | Get-ADUser -Property * | Select SamAccountName, DisplayName, Office | Export-csv c:\work\leaders.csv
Import-Csv c:\work\Leaders.csv | ForEach-Object {Get-AdUser $_.SamAccountName -Property DirectReports | Select-Object -ExpandProperty DirectReports | Get-Aduser -Property * | Select SamAccountName, DisplayName, Office} | Export-csv c:\work\leaders1.csv
Import-csv C:\work\leaders.csv | Foreach-Object If (!(Get-ADUser $_.SamAccountName –properties MemberOf).MemberOf –like “$listname”) {Add-ADGroupMember $listname –member $_.samAccountName}
Import-csv C:\work\leaders1.csv | Foreach-Object If ((Get-ADUser $_.SamAccountName –properties MemberOf).MemberOf –like “$listname”) {Add-ADGroupMember $listname –member $_.samAccountName}
if ((Get-ADUser $user -Properties MemberOf).memberOf -like "$listName") {
Write-Host -ForegroundColor Green "$user is already a member of $listName"
} else {
Write-Host -ForegroundColor Yellow "Adding $user to $listName"
Add-ADGroupMember $ListName -member $user
}
And here is the error I keep getting:
[PS] C:\work>.\leader.ps1
Unexpected token '{' in expression or statement.
At C:\work\leader.ps1:25 char:143
+ Import-csv C:\work\leaders.csv | Foreach-Object If (!(Get-ADUser $_.SamAccountName â?"properties MemberOf).MemberOf â?"like â?o$listnameâ
??) { <<<< Add-ADGroupMember $listname â?"member $_.samAccountName}
+ CategoryInfo : ParserError: ({:String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
Quick answer when using -like you need to be less specific with your criteria.
-like "*$Listname*"
Like is looking for that specific text at the beginning of the item to be
searched. If that item can appear anywhere in the memberof then you need to either add the wildcards or use -match instead. -match implies * around your search item.
Since most responses from that command should start with
CN=
Your member group will not be the first thing it finds
Hope that helps
Difference between -like and -match

Powershell - CSV - AD Attribute Update

I'm trying to get AD attributes updated with information from my payroll system. I have a good dump of employee information, and can get most things updated, but I'm having some small problems that hopefully someone much better with Powershell than I can assist with.
--- UpdateInfo.ps1 ---
Import-Module ActiveDirectory
$Users=Import-Csv C:\info_update.csv
foreach($u in $Users)
{
Get-ADUser -Filter "employeeID -eq '$($u.employeeID)'" -properties * | set-aduser -replace #{title="$($u.title)";extensionAttribute1="$($u.title)";givenName="$($u.givenName)";initials="$($u.initials)";middleName="$($u.middleName)";sn="$($u.sn)";physicalDeliveryOfficeName="$($u.physicalDeliveryOfficeName)";streetAddress="$($u.streetAddress)";l="$($u.l)";st="$($u.st)";co="$($u.co)";countryCode="$($u.countryCode)";c="$($u.c)";postalCode="$($u.postalCode)";department="$($u.department)"}
}
--- info_update.csv ---
employeeID,givenName,initials,middleName,sn,name,title,physicalDeliveryOfficeName,streetAddress,l,st,co,countryCode,c,postalCode,department,manager
"111","Smith","Q","Quincy","John","Smith, John Q.","Tech II","Springfield, IL","800 E Monroe St.","Springfield","IL","United States","840","US","62701","IT","540"
Two questions:
I can't get the 'name' field to update. I thought that it was because of the space, but the physicaldeliveryofficename has a space, too...and it's working fine.
I need to do a lookup for the manager ID (last column), return the DN of the manager, and use that to update the manager attribute.
If anyone can help, I would greatly appreciate it. I feel like I'm really close, but I'm overlooking something.
Thanks!
---UPDATE---
Thanks to #TheMadTechnician
Here's the final answer.
Import-Module ActiveDirectory
$Users=Import-Csv C:\Job_titles.csv
foreach($u in $Users)
{
$Mgr = Get-ADUser -Filter "employeeID -eq '$($u.manager)'" | Select -ExpandProperty DistinguishedName
Get-ADUser -Filter "employeeID -eq '$($u.employeeID)'" -properties * | set-aduser -replace #{title="$($u.title)";extensionAttribute1="$($u.title)";givenName="$($u.givenName)";displayName="$($u.name)";initials="$($u.initials)";middleName="$($u.middleName)";sn="$($u.sn)";physicalDeliveryOfficeName="$($u.physicalDeliveryOfficeName)";streetAddress="$($u.streetAddress)";l="$($u.l)";st="$($u.st)";co="$($u.co)";countryCode="$($u.countryCode)";c="$($u.c)";postalCode="$($u.postalCode)";department="$($u.department)";manager="$Mgr"} -PassThru | Rename-ADObject -NewName "$($u.name)"
}
So we will use get-aduser and filter on EmployeeID for the manager, and use Select -ExpandProperty for the DistinguishedName property. I also use the -PassThru switch on your Set-ADUser, and pipe it to Rename-ADObject. See how that suits you:
Import-Module ActiveDirectory
$Users=Import-Csv C:\info_update.csv
$Managers = Import-Csv C:\Managers.csv
foreach($u in $Users)
{
$Mgr = Get-ADUser -Filter "employeeID -eq '$($u.manager)'" | Select -ExpandProperty DistinguishedName
Get-ADUser -Filter "employeeID -eq '$($u.employeeID)'" -properties * | set-aduser -replace #{title="$($u.title)";extensionAttribute1="$($u.title)";givenName="$($u.givenName)";initials="$($u.initials)";middleName="$($u.middleName)";sn="$($u.sn)";physicalDeliveryOfficeName="$($u.physicalDeliveryOfficeName)";streetAddress="$($u.streetAddress)";l="$($u.l)";st="$($u.st)";co="$($u.co)";countryCode="$($u.countryCode)";c="$($u.c)";postalCode="$($u.postalCode)";department="$($u.department)";manager="$Mgr"} -PassThru | Rename-ADObject -NewName "$($u.name)"
}
Set-ADUser cannot be used to set Name. See http://technet.microsoft.com/en-us/library/ee617215.aspx
Try using Rename-ADObject:
Rename-ADObject [-Identity] <ADObject> [-NewName] <string>
Source: http://technet.microsoft.com/en-us/library/ee617225.aspx