Need assistance with PowerShell Script to clean up computers in AD that meet criteria - powershell

Hello & thanks in advance for the help!
Looking to delete computers (Workstations OU) in AD if they meet a certain criteria.
I need to make sure they have the "LOCATION," part of the Canonical name in common before proceeding to delete. If they are not at my location that could be reason to investigate and I do not want to delete them. This is an example of one PC (Caps are fields I changed):
ORGANIZATION.COM/Workstations/BUSINESS UNIT/Desktops/LOCATION/COMPUTER NAME
I have the following script currently that will print them to a .csv which is helpful, but to take it one step further, it would be nice to print this on the screen then review it quick and proceed with a delete. Any tips??
Get-Content C:\Temp\Powershell\hosts.txt | ForEach-Object {
Get-ADComputer $_ -Properties Name,CanonicalName |Select-Object Name,CanonicalName
} -ErrorAction Ignore | Export-Csv C:\Temp\Powershell\Output.csv
Or even a second line of code I can utilize the output.csv with, not sure where to go from here...
Again, Thanks!

Added -Recursive and it seems to be working as expected.

Related

Learning Powershell scripting

I am a young I.T Apprentice who is responsible (in part)for administering Active Directory tasks.
I have looked to learn powershell to help with this.
Anyway, I'm looking to incorporate reading data from files into my daily tasks to simplify a process, I'm looking to pull data and configure Changes for multiple AD accounts. My idea is to have a file with the samaccountname listed in a single column (with no header). Import the csv file to get the ad username and disable the users then place a new description in the accounts description field.
Right now I have a csv with usernames listed and a script that imports the csv and this is where I'm stuck.
I can execute the disable-aduser and set-aduser -description "sample text", functions I need for the script separately , successfully in testing in a one liner situation by calling on the get-aduser and piping the result to each command, but I'm looking to place this in a script and grab the ad usernames from a csv for multiple accounts.
I'm having trouble setting the object variable from the csv (i hope that's the right terminology), I have been unable to 'get this' for lack of a better term. I'm hoping to place this into a for loop to include the functions I have described.
Can anyone help me or describe how I can set the variables to encapsulate each ad user account in my file to help me continue on with my script and configure the changes above?
I know this may seem like a strange or overly simple question to ask I.T pros but I can assure you I have done further reading but I havent been able to find a resolution to this specific problem.
My apologies if the terminology in my question is not spot on.
Thank you in advance, Glenn.
here's one way to loop thru a collection of items imported from a CSV file ...
# fake reading in a headerless, one-column text file as a CSV
# in real life, use Import-CSV
$UserNameList = #'
OneTest
TwoTest
ThreeTest
FourTest
'# | ConvertFrom-Csv -Header UserName
foreach ($UNL_Item in $UserNameList)
{
# do the things you need done to each user id here
'Acting on user [ {0} ] ...' -f $UNL_Item.UserName
}
hope that helps,
lee
The below will load the entire CSV and show it in an Out-GridView. You can then CTRL click multiple users and process them that way.
I enjoy doing it this way in the event that another name has snuck into my CSV when it should not have,
Import-CSV 'C:\Location\of\CSV.csv' | Out-GridView -PassThru | ForEach-Object{Disable-ADAccount $_.SamAccountName; Set-ADUser -Identity $_.SamAccountName -Description "Test Description"}
NOTE: Thanks Robert for advice of skipping putting the Import-csv into a variable to handle and going straight to the source.

Need to scan all domain computers for .pst files

I am new to powershell sctipting, like Brand new. I have some experience using Exchange powershell but thats always been for very specific items like adjust calendar permissions and such. Nothing to robust.
Currently I am working on a powershell script to push out via Group policy that will run a a search on each domain PC. I've been getting help from a co-worker but he isn't available right now and I have a hard time following him sometimes. I am this site and its user might be able to assist me. What I am trying to do(and I believe I am close to) is pulling a list of drives for each computer on the domain. Once I pull that list O pipe it into a variable and then do a search on that variable for any files that end with .pst. Once the search is complete if there were results from the search a file should be created with the FUllname"path" of each file and the computer name should be used for naming the file. If there are no results form the search the file would be empty but the filename should still be named after t he computer. I believe I have gotten everything correct except that I do not know how to name the file based on the computer name. Thank you for your time and help with this.
Here is my code so far:
$drives=Get-WmiObject -query "SELECT * from win32_logicaldisk where
DriveType = '3'" | select deviceid
foreach ($drive in $drives){
$pstfound=Get-ChildItem $drive.deviceid *.pst -recurse | select
fullname
$pst+=$pstfound
}
IF ($pst -eq $null) {
$pst | Out-File \\"Servername"\Searchresults\Null
} Else {
$pst | Out-File \\"Servername"\Searchresults\HasItems
}
Thank you. I wasn't initially planning on using the UNC path but changed it up anyways and I think that will make it easier to go through later. I also figured out my issue for naming the file generated after the computer it ran on. I just set a variable $hostname=hostname and then set the files as \$hostname.csv

Powershell script to update Active Directory attribute

I have limited exposure to Powershell so I need some help.
I have a CSV file with just the SamAccounName. I would like to use powershell to import that file and update the employeeID attribute with the sammaccountname value. The import is the easy part:
$users = Import-Csv c:\filename.csv
Using the file to update the employeeid attribute is what I need help with. Thanks in advance for your help.
There is some great documentation about this here so you can get a good idea about this: https://technet.microsoft.com/en-us/library/ee617215.aspx
With RSAT Running you need to Import the AD Cmdlet's Import-Module ActiveDirectory
Once this is done you are starting to head down the appropriate path, try working with the following:
Import-CSV $csvFile | forEach { Set-ADUser $_.SamAccountName -EmployeeID $_.SamAccountName -WhatIf }
This can go much further, have a look at the top link instead of copying and pasting this code as you don't want to make error on this. But there should be enough information here to get you up and running.
Note the '-WhatIf' in the above code means PoSh will tell you what will happen rather than making it happen.

Get Memberships Of User

I have a very simple question but for some reason I can't seem to get my head around it.
I need a line of code that could be ran as a user from a client and lists all the "memeber of" groups from the AD (ONLY FOR THIS CURRENT USER). similar to
Get-ADGroupMember -identity "domain admins" -Recursive | foreach{ get-aduser $_} | select SamAccountName,objectclass,name
I would like the result to be listed.
I either need a way to import the AD module on a client computer or another way to contact the DC and get the users current "memeber of" groups.
/Niklas
I found the best way for my needs but CB.'s answer worked as well!
[ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1'
I can then keep using this output in my code
you can use dos command line:
net user /domain %username%
The easiest way to do this would be with
Get-ADPrincipalGroupMembership -identity "Username"
Now this also means that you would have to have the active directory module loaded which you can find more information on its use on Technet Get-ADPrincipalGroupMember
If you simply want to produce a list, make a call to the command prompt as I find this works well, although it does truncate group names:
net user %username% /DOMAIN
If you want to programmatically get them and easily do something with that data, you'll want to rely on the Active Directory cmdlets.
To determine if you have these readily available in Powershell, you'll need to run the following command:
Get-Module –ListAvailable
If you don't see ActiveDirectory in the list you will need to first download and install the Windows Management Framework and import the module yourself:
Import-Module ActiveDirectory
Once that's done I believe this command should do the trick:
(Get-ADUser userName –Properties MemberOf | Select-Object MemberOf).MemberOf
Hopefully that gets you started. I'm fairly certain that there's more than one way to accomplish this with Powershell. Take a look at the Microsoft TechNet documentation to see if you can find something that better suits your needs.
Personally I have only ever needed to query AD group memberships ad-hoc for diagnostic purposes and have always relied on Get-ADUser or the command line call, depending on the target audience of the resulting data.

PowerShell: Compare CSV to AD

I'm fairly new to PowerShell and I'm posting this on many forums but I've had success with programming assistance from here before and although this isn't strictly programming, I was hoping someone might know the answer.
My organization had about 5,300 users we needed to disable for a client. Someone decided the best use of our time was have people go through AD and disable them one at a time. Soon as I got wind of this I put a stop to it and used PowerShell to take the CSV list we already had, and ran a cmdlet to disable all of the users in the CSV list.
This appeared to work, but I wanted to run a comparison. I want to compare the users from the CSV file, to the users in AD, and confirm that they are all disabled without having to check all 5300 individually. We checked about 60 random ones to verify my run worked, but I want to make sure none slipped through the cracks.
I've tried a couple scripts and I've tried some variations of cmdlets. None of the scripts I tried even worked, spammed with errors. When I try to run a search of AD either using get-content or import-CSV from the csv file, when I export its giving me about 7600 disabled users (if I search by disabled). There were only 5300 users in total, so it must be giving me all of the disabled users in AD. Other cmdlets i've run appear to do the same thing, its exporting an entire AD list instead of just comparing against my CSV file.
Any assistance anyone can provide would be helpful.
Without knowing the exact structure of your CSV I'm going to assuming it is as such:
"CN=","OU=","DC="
"JSmith","Accounting","Foo.com"
"BAnderson","HR","Foo.com"
"JAustin","IT","Foo.com"
That said, if your first field actually has CN= included (i.e. "CN=JSmith","OU=Accounting","Foo.com") you will want to trim that with .TrimStart("CN=").
$ToRemove = Import-CSV UserList.csv
$UserList=#()
ForEach($User in $ToRemove){
$Temp = ""|Select "User","Disabled"
$Temp.User = $User.'CN='
If((Get-aduser $Temp.User -Prop Enabled).Enabled){$Temp.Disabled='False'}else{$Temp.Disabled='True'}
$UserList+=$Temp}
$UserList|?{$_.Disabled -eq 'False'}
That loads the CSV into a variable, runs each listing through a loop that checks the 'CN=' property, creates a custom object for each user containing just their name and if they are disabled, and then adds that object to an array for ease of use later. In the end you are left with $UserList that lists everybody in the original CSV and if they are disabled. You can output it to a file, filter it for just those that are still enabled, or whatever you want. As noted before if your CSV actually has CN=JSmith for each line you will want to update line 5 to look as such:
$Temp.User = $User.'CN='.TrimStart("CN=")
If you don't have any headers in the CSV file you may want to inject them. Just put a line at the top that looks like:
CN=,OU=,DC=
Or, if you have varying OU depths you may be better off doing a GC and then running each line through a split, taking the first part, trimming the CN= off the beginning, and checking to see if they are disabled like:
GC SomeFile.CSV||%{$_.split(",")[0].trimstart("CN=")|%{If((get-aduser $_ -prop enabled).enabled){"$_ is Enabled"}else{"$_ is Disabled"}}}
Assuming your CSV has a column called DN you can run the following which will return all users from your spreadsheet which are enabled
import-csv YourUsersCSV.csv | Get-ADUser -Filter
{DistinguishedName -eq $_.DN } |
where{$_.enabled -eq $true} |
Select-Object -Property DistinguishedName,samaccountname,enabled