I need to run a script that moves computers to a specific OU every time they are created. I have been researching about it, and I know that I can trigger a script with a scheduled task every time that the event log 4741 is created. The thing is that, how can I get the computer name from this event log to include it in my script.
My script will be something like this:
if ('New computer name' -match '^ORD\d{3}$'){
Get-ADComputer "New computer name" | Move-ADObject -TargetPath "OU=X,DC=X,DC=X"
}
I'm pretty confused hehe
Thanks in advice
Update:
I've been testing and I have written this command line:
Get-EventLog -LogName Security -InstanceId 4741 -Newest 1 | Select-Object -Property *
The only thing I need is to get the right property. The thing is that I can't get the SamAccountName as it's not a property per se. When i run this:
Get-EventLog -LogName Security -InstanceId 4741 -Newest 1 | Select-Object -Property SamAccountName
I get an empty column. I almost got it!
CodePudding user response:
I would use the newer Get-WinEvent cmdlet and parse out the information from the XML.
Try
# by default, Get-WinEvent returns event information in the order of newest to oldest.
foreach ($event in (Get-WinEvent -FilterHashtable @{LogName='Security';ID=4741})) {
# convert the event to XML and grab the Event node
$eventXml = ([xml]$event.ToXml()).Event
# with this event, you can also parse out the 'TargetUserName' instead of 'SamAccountName'
# if need be, you can get the computer SID using ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'TargetSid' }).'#text'
$computerName = ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'SamAccountName' }).'#text'
if ($computerName -match '^ORD\d{3}$') {
Get-ADComputer $computerName | Move-ADObject -TargetPath "OU=X,DC=X,DC=X"
# you can exit the foreach loop here if you want with the break statement:
# break
}
}