How to create specific user log files in PowerShell? - 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"

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.

powershell write to file

I've written a GUI for making changes in AD and I need every action logged. This GUI is used by multiple users at once and writes to one file but only first person that writes to the log file can actually write to it. Everyone else has access denied.
I'm using streamwriter like this.
$File = "$LogPath\$LogDate.log"
$stream = [System.IO.StreamWriter] $File
$stream.WriteLine("----------------------------------------------------")
$stream.WriteLine("$LogTime $ExecUser | Set expire date for user $setenddateuser to $usernewenddate")
$stream.close()
What am I doing wrong here that the handle for this file is not released for someone else to use?
Creating a stream basically blocks the access or the creation of other streams for any files, unless it's al xlsx in sharemode, what I do with the log similar logs is to use add-content.
I.e:
Add-content -value "test" -path $logRoute
Sorry for any typos, I'm on my cell atm. But that should fix your issue
Have you tried using a fine-grained .NET mutex? Each time you need to log a message, lock the mutex, use Add-Content to append the message, then release the mutex. That should make sure the file is never opened multiple times simultaneously, which is almost certainly the cause of your problem.
Here's an article on almost exactly this issue.
Using ACL commands helped to fix the issue as the newly created file was lacking perrmissions for write for other users.

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

preplog.exe ran in foreach log file

I have a folder with x amount of web log files and I need to prep them for bulk import to SQL
for that I have to run preplog.exe into each one of them.
I want to create a Power script to do this for me, the problem that I'm having is that preplog.exe has to be run in CMD and I need to enter the input path and the output path.
For Example:
D:>preplog c:\blah.log > out.log
I've been playing with Foreach but I haven't have any luck.
Any pointers will be much appreciated
I would guess...
Get-ChildItem "C:\Folder\MyLogFiles" | Foreach-Object { preplog $_.FullName | Out-File "preplog.log" -Append }
FYI it is good practice on this site to post your not working code so at least we have some context. Here I assume you're logging to the current directory into one file.
Additionally you've said you need to run in CMD but you've tagged PowerShell - it pays to be specific. I've assumed PowerShell because it's a LOT easier to script.
I've also had to assume that the folder contains ONLY your log files, otherwise you will need to include a Where statement to filter the items.
In short I've made a lot of assumptions that means this may not be an accurate answer, so keep all this in mind for your next question =)

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