Powershell Basics

Good Morning Everyone,

New to the forum and also new to powershell. I have created a script that goes to the DC and discovers new Users with these particular lines:
$lastday = ((Get-Date).AddDays(-1))

Get-ADUser -filter {(whencreated -ge $lastday)} -properties DistinguishedName, whencreated | Select-Object Name, UserPrincipalName, SamAccountName, DistinguishedName, whencreated | Format-Table Name, UserPrincipalName, SamAccountName, DistinguishedName, whencreated

The above line works in my New_User Script, So now I am trying to discover new OUs in the same environment and obviously the properties of ADOrganizationalUnit does not allow me to use the same type of Algorithm (for the lack of a better term) . Not sure what to do from here, any help would be much appreciated. So I am trying to do the same thing but I am not good enough to figure this out.

Get-ADOrganizationalUnit -Filter 'Name -like ""’ -Properties Created | Format-Table DistinguishedName -A*

The results of the above line are as follows:
OU=Obsolete Computers DO NOT DELETE,DC=caa,DC=local
OU=Obsolete Groups - DO NOT DELETE,DC=caa,DC=local

The above line is the only way I could get the OU names and Distiguished names.

Thanks,
Michael

Michael,
welcome to the forum.

First … when you post code, error messages, console output or sample data please format it as code using the “preformatted text” button ( </> ).

Thanks in advance.

I’m a little unsure about what you want to achive. If you use the filter “... -like” … with an empty string what do you expect to get in return? If you’re looking for ALL OUs you should use “... -like '*'
So it should look something like this:

Get-ADOrganizationalUnit -Filter "Name -like '*'" -Properties Created | 
    Select-Object -Property Name, DistinguishedName,Created

… (untested … I don’t have an AD to test at them moment :wink: )

Thank you Olaf, I will do that for now on I am sorry for the foul up.

# NewUser Accounts Powershell script ###
$lastday = ((Get-Date).AddDays(-1))
$filename = Get-Date -Format yyyy.MM.dd
$DNAME=Get-ADUser -filter {(whencreated -ge $lastday)} -properties DistinguishedName
$exportcsv="c:\temp\new_ad_users_" + $filename + ".csv"
Get-ADUser -filter {(whencreated -ge $lastday)} -properties DistinguishedName, whencreated | Select-Object Name, UserPrincipalName, SamAccountName, DistinguishedName, whencreated | Format-Table Name, UserPrincipalName, SamAccountName, DistinguishedName,  whencreated

Get-ADUser -filter **{(whencreated -ge $lastday)}** -properties DistinguishedName, whencreated | Select-Object Name, UserPrincipalName, SamAccountName, DistinguishedName, whencreated | Export-csv -path $exportcsv
#Out-File -FilePath c:\temp\output.txt

The above is what I am trying to do (The one above actually works). I need to get the list of new OUs created in the last 24 hours.
Below is what I am using to get OU names:

# New OUs Powershell script ###
$lastday = ((Get-Date).AddDays(-1))
$filename = Get-Date -Format yyyy.MM.dd
$exportcsv="c:\temp\new_ous_" + $filename + ".csv"

# This is for output in Terminal/Powershell
Get-ADOrganizationalUnit -Filter 'Name -like "*"' -Properties Created  | Format-Table DistinguishedName -A
#Get-ADOrganizationalUnit -Filter * -Properties Created | Format-Table Name, Created
# Formatted for CSV File. #
Get-ADOrganizationalUnit -Filter 'Name -like "*"' -Properties Name, Created | Select Name, Created, DistinguishedName | Export-csv -path $exportcsv
#Out-File -FilePath c:\temp\output.txt


Thank you very much,
Michael

Hmmm … I’m still a little unsure what you want to do.

First … I’d not query the AD twice for the same objects. Instead save the output of one query and use it.
Second … most of the time I’d rather not use format cmdlets as they turn rich and powerful objects into stupid pixels on the screen.

$Yesterday = (Get-Date).Date.AddDays(-1)

$OUList = Get-ADOrganizationalUnit -Filter 'Name -like "*"' -Properties Created  
$OUList | Select-Object -Property DistinguishedName, created

$OUList | 
    Where-Object -Property Created -GT -Value $Yesterday |
        Select-Object -Property Name, Created, DistinguishedName | 
            Export-Csv -Path $exportcsv -NoTypeInformation

Thank you sir, for the record I need to see if there is a new OU created with in the last 24 hours because our ad environment is getting extremely clutered or litered with unauthorized objects being created and now i am having to clean all those up so this will allow me to control when and where objects are created.

Thank you by the way,

Sure. :wink: Does that mean your question is answered? :face_with_raised_eyebrow:

It sure does and it actually works now. Thank you. Your suggestion got me where I needed to get. I just need to figure out how to display the message in both the email and the Teams Card.

I know there is a variable I should be able to use (to display the new OU) like in the following line

"text"       = "Check for the OU created in -> <Variable Here> "

Here is the full script as it is now:

# New OUs Powershell script ###
$lastday = ((Get-Date).AddDays(-1))
### Test ###
$filename = Get-Date -Format yyyy.MM.dd
$exportcsv="c:\temp\new_ous_" + $filename + ".csv"

$OUList = Get-ADOrganizationalUnit -Filter 'Name -like "*"' -Property Created
$OUList | Select-Object Name, DistinguishedName, Created

$OUList | 
    Where-Object -Property Created -ge -Value $lastday |
        Select-Object -Property Name, Created, DistinguishedName | 
            Export-Csv -Path $exportcsv -NoTypeInformation


Send-MailMessage -From "CRAA <craa@ushere.com>" -To "Tony <tcentofanti@ushere.com>", "Michael <mcooper@ushere.com>" -Subject "There is a New OU in the environment" -Body "There is a new OU $SON in the environment..." -Attachment "c:\temp\new_ad_users_2021.06.22.csv" -SmtpServer smtp.ushere.com -Port 25

### Work on This to send Teams Alerts ###
[String]$var = "This is a test"
$JSONBody = [PSCustomObject][Ordered]@{
    "@type"      = "MessageCard"
    "@context"   = "http://schema.org/extensions"
    "summary"    = "A new OU has been created in the environment, please investigate!"
    "themeColor" = '0078D7'
    "title"      = "New OU created in the Environment"
    "text"       = "Check to see the OU created in -> <Variable Here> "
}
$TeamMessageBody = ConvertTo-Json $JSONBody -Depth 100
 
$parameters = @{
    "URI"         = 'https://ushere0.webhook.office.com/webhookb2/8176eefe-de88-4afd-bec8-7c37090ab9eb@b98364ec-c180-4324-9bbe-4d7d8d69af94/IncomingWebhook/bc9685b9f35f435bb0fb1a2380cf9eb1/bed40505-1b34-49de-b31b-0332121323db'
    "Method"      = 'POST'
    "Body"        = $TeamMessageBody
    "ContentType" = 'application/json'
}
Invoke-RestMethod @parameters

All i need is the variable to plugin to make it complete.

Thanks for your help,
Michael

Great. I’m glad it helped.

Sorry, I didn’t get that. What variable do you need?

Hello Olaf,

I apologize for my stupidty if I am not explaining correctly. I will try to be more to the point here.

So with what you gave me I got it to work and it does identify the New OU
new_ou_script-1
I need to capture that information and provide it via the email and teams card alert. I assume it is being captured via your part you gave me:

$OUList | 
    Where-Object -Property Created -ge -Value $lastday |
        Select-Object -Property Name, Created, DistinguishedName

How do I capture the data from this function (for the lack of knowing what it’s called)
I am thinking a variable and just plug the variable in where I need it. Is that possible?

Because when I use the $OUList it gives all 293 OUs. I only need the one that your function(?) captures. I know I am new and stupid to this, but I am actually learning it.

Thanks,
Michael

If the output seen is what you’re trying to collect, simply save the output to a variable like this

$newvariable = {code that produces desired output}

In other words, just make up a variable name (meaningful hopefully) and put that with an equals sign before your code. The only time this wouldn’t work as expected is if you were using Write-Host to create the output.

1 Like

Thank you sir, I will give that a shot, I appreciate the help.

Thanks,
Michael

Well the result of the algorithm has to be passed to email and a teams card that I created. So every one sees them. I already have the email and teams part working. I just need to learn how to grab the results and pass them to those two ways of alerting.

Thanks,

I don’t know if it is my lack of knowledge of the english language but I’m a kind of confused by your replies. In one sentence you say you have both parts working and the next sentence is that you need to learn how to make both parts working.

For me it would be very helpful if you ask a specific clear question. :wink:

I am sorry Olaf, I am sure it’s my lack of being able to explain it properly. Let me try to form a reasonable explanation and I will post in a while.