问题
I have made a script to create a homefolder(by the name of SAMAccountname) for a newly created AD user.
$ADServer = 'xyz1'
Import-Module ActiveDirectory
$searchbase = "OU=xyz2,OU=xyz3,DC=xyz4,dc=xyz5"
$ADUsers = Get-ADUser -Filter {name -eq "xyz6"} -Server $ADServer -SearchBase $searchbase -Properties *
New-Item -ItemType Directory -Path "xyz7\$($ADUsers.sAMAccountname)"
Everything is automated except the fact that I have to feed in the name of the user (AD account name) to make it search for that particular user. I want to change this process. I want to make this automated thru a scheduled run.
Now, I want to query the eventlog and search for EVENTID = 4720 (ie "a new user is created") and trap the SamAccountName of this newly created user (under attributes [I have checked]) and pass this in my current script... so that if I run the overall script by scheduled run, it will detect the new user creation and automatically make its homefolder.
回答1:
$a = (Get-EventLog System | Where-Object {$_.EventID -eq 514}).message
Should allow you to get back the information you want. You can then split the result to parese out the SAM name.
"514" is just my example - you'll need to replace that with what ever EventID you want to track.
linky Has more info on how to use get-eventlog to filter the results
回答2:
For extracting the account names created within the last 30 minutes you could use a regular expression like this:
Get-EventLog Security -Computer SERVERNAME -After (Get-Date).AddMinutes(-30) |
Where-Object {
$_.EventID -eq 4720 -and
$_.Message -match "sam account name:\s+(.*)"
} | ForEach-Object { $matches[1] }
With that said, an ultimately better approach would be to integrate home directory creation in the user creation process, i.e. create the directory when you create the user (since you already have the account name at that point).
来源:https://stackoverflow.com/questions/31721386/automating-the-creation-of-homedrive-of-a-newly-created-ad-user