Learning Powershell scripting - powershell

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.

Related

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

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.

How to create specific user log files in PowerShell?

I know there are question that is already answered however those are the log files I don't need and I can't get it to work. This part of PowerShell is something I didn't learned yet. I'm trying to do the following: I wrote a script to create users, mailboxes, folders etc however I want to enable a log file, just simple and plain.
Something only certain people can access and where the log files have the following info, for example: PSmith created on 01/29/2019 the user account JDoe.
How can I do this? I tried a lot found online however I have to rewrite my whole script for some to work.
Easiest option: you can enable transcript which would log every single command that is entered at the console potentially creating a huge file but you would have to filter for the specific messages yourself.
There are tools like microsoft orchestrator that would run your script and log the results automatically but those are expensive other than that you would pretty much have to build the logging yourself.
My suggestion would be to send the message to the windows event logs. This way you dont have to manage the log files, windows does it for you with date and time stamps. This would also make it audit and query friendly.
I believe you need something like this, if not please provide more code.
$creator = (get-aduser $env:username | Select Name).Name
$date = get-date -UFormat "%d/%m/%Y"
I believe you have the $user in your script.
$log = $creator + "created on " + $date + " the user account " + $user.Name
Out-File $log "C:\temp\log.csv"

How to change multiple telephone numbers in AD from a CSV

Good Morning Everyone,
I have a list of users (about 200 samAccountName's) and the only field that needs to be updated in AD is the telephoneNumber field. Example user John Smith Telephone number is 44444 and needs to be changed to 12345. Im guessing the csv file would contain a column for samAccountName, and the 2nd column would be telephoneNumber which would be a list of the numbers that are going to overwrite whatever the users current number is in AD.
i was thinking i could use the script from #Henrik Stanley Mortensen and modify it, but not sure what fields to change. THis is the url from my 1st question....
How to edit only the Firstname (givenName) of multiple users and import with csv
First let me say I agree stack is not a code generation site. It goes a long way if you have a little bit of code to show as to what you have tried. Even if it is TERRIBLE others in the community will feel compassion and empathy towards you versus negativity. Second please go to amazon and buy the book "Learn Powershell in a Month of Lunches" This will help you a ton and get your fundamentals down. Real easy read.
https://www.amazon.com/Learn-Windows-PowerShell-Month-Lunches/dp/1617294160/ref=sr_1_3?ie=UTF8&qid=1533311287&sr=8-3&keywords=powershell+books
Ok now off my soapbox. So I have created a csv called updatetelphones.csv and placed it in my C:\temp folder on my desktop. It has two columns one called SamAccountName and a second Called TelephoneNumber. Notice no spaces. With powershell we want to import that into a variable then iterate through each item and set the phone number for the user.
$UsersToUpdate = import-csv -Path "C:\temp\updatetelephones.csv"
foreach($User in $UsersToUpdate)
{
Set-ADUser -Identity $User.SamAccountName -OfficePhone $User.TelephoneNumber -WhatIf
}
Above is the powershell code. Now look carefully at the end of my set-aduser command I have a -whatif. ANYTIME you are making changes to AD I recommend you test your script with the -whatif first. That simulates the changes but doesn't make any so you can confirm it is accurate. So use this to test on your side. Once you validate remove the "-whatif" and run to actually make the changes. Peace and Happy powershell learning!!
it is strange, I use telephonenumber as a Get-ADUser property but OfficePhone as a parameter to set the telephonenumber property
Set-AdUser -Identity $user.SID -Credential $credential -OfficePhone $vp_telephonenumber -Server DC2.abc.com

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

Simple PowerShell Script to loop through 1 CSV file to create a new CSV file from another

I know the title sounds confusing, but once I describe this, I'm certain there is a very easy way to perform what I need to do. I'm very new to PowerShell and am trying to perform a specific task that seems rather difficult to find a good answer for one the Web.
I have spent the past several days searching through methods of concatenating the data and joining the files together, but nothing that was specific enough to this task. All examples show how to display data, but nothing that loops through and adds data together to create a new csv file. If anything, I've over-researched this issue to the point of having to pose this message to see where I can get my brain de-cluttered with all of the useless options I've already tried...
I have two csv files. I call them csv's, but they are really just a single column of information each.
Files:
Users.csv
Offices.csv
The Users.csv file has a list of network user names. The Offices.csv file has a list of numbers that correspond to office locations.
What I want to have happen is to use a loop that will take each user from the users.csv file and create a new line in a separate csv file the adds each of the offices to it.
EXAMPLE:
Users.csv
NTNAME
domain\user1
domain\user2
domain\user3
Offices.csv
OFFICES
0001
0023
0043
0067
When combined, I would like csv file that looks like this:
NTNAME,OFFICES
domain\user1,0001
domain\user1,0023
domain\user1,0043
domain\user1,0067
domain\user2,0001
domain\user2,0023
domain\user2,0043
domain\user2,0067
domain\user3,0001
domain\user3,0023
domain\user3,0043
domain\user3,0067
Any help you can give would be greatly appreciated...
Borrowing Shay's awesome CSV field enumeration code:
$offices = Import-Csv 'C:\path\to\offices.csv'
Import-Csv 'C:\path\to\users.csv' | % {
foreach ($prop in $_.PSObject.Properties) {
$offices | select #{n=$prop.Name;e={$prop.Value}}, OFFICES
}
} | Export-Csv 'C:\path\to\combined.csv' -NoTypeInformation