I am trying to get a list of all Exchange mailboxes that have inbox rules. I am able to get a list of all mailboxes and a count of how many rules each mailbox has. I am trying to skip or have no output for mailboxes with zero rules.
$mailboxes = get-mailbox
foreach ($mailbox in $mailboxes) {
Write-Output $mailbox.id,((Get-InboxRule -Mailbox $mailbox.id)| Measure-Object | select count)
}
Current code outputs:
User1
0
User2
11
User3
0
User4
1
User5
0
etc....
I am looking to only output user's who have inbox rules.
Thanks-
#!/usr/bin/env powershell
get-mailbox -resultsize unlimited |
ForEach-Object {
Write-Output -Message ('Checking {0}...' -f $_.alias) -Verbose
$inboxrule = get-inboxrule -Mailbox $_.alias
if ($inboxrule) {
foreach($rule in $inboxrule){
New-Object -TypeName PSObject -Property #{
Mailbox = $_.alias
## you could uncomment this if you wanted more information
##Rulename = $rule.name
##Rulepriority = $rule.priority
##Ruledescription = $rule.description
}
}
}
} |
Export-csv -Path "$env:userprofile/desktop/export.csv" -NoTypeInformation
This should give you a list of just the users who have rules.
Not exactly sure what your expected is but to answer how to exclude those mailboxes with no inbox rules:
foreach($mailbox in Get-Mailbox) {
$ibxrules = #(Get-InboxRule $mailbox.Id).Count
if($ibxrules -eq 0) {
continue
}
[pscustomobject]#{
MailboxId = $mailbox.Id
InboxRules = $ibxrules
}
}
To explain the use of #(...) around Get-InboxRule, this is to ensure the output is always an array, and this also ensures we can always get a .Count out of it.
Related
I have a list of groups that i need to pull back all users. I am aware due to the numbers it is restricted. I have tried adding page size but it does not work.
Here is the code
Get-Module ActiveDirectory - ErrorAction silentlycontinue
Function resolve-group}
param ($group)
For each ($member in $group.member){
$obj = [ADSI] ("LDAP://" + member)
if (obj.objectclass[1] -eq 'group'){resolve-group $obj}
else {
If ($obj.employeeid.length -eq 6)
{
$displayname = $obj.displayname
$employeeid = $obj.employeeid
$groupname = $group.name
$global:members +="$employeeid,$displayname,$groupname"
}
}
}
}
$global:members =#()
$group = [ADSI] "LDAP://cn=ab,ou=cd,ou=ef,DC=gh,DC=BB"
resolve-group $group
$group = [ADSI] "LDAP://cn=aa,ou=cc,ou=ef,DC=gh,DC=BB"
resolve-group $group
"ID,Name,Group" > c:\test\groups.csv
$global:members | sort-object - unique >> c:\test\groups.csv
I don't know how to amend the script to add and increase the page size?
I have only listed a couple of the groups but there are 100's of groups
Thanks
I have in my terminate user script, some code that checks the size of the user's 365 mailbox before converting to a shared mailbox. This is the procedure for some clients. If the mailbox is greater than 50GB, the script should notify the admin and not proceed to convert, or else it'll eventually be deleted without a 365 license assigned.
$TotalItemSize = Get-MailboxStatistics $termUserPrincipalName | Format-Table TotalItemSize -hidetableheaders | Out-String
$Value = $TotalItemSize.Split("(")[1].Split(" ")[0].Replace(",","")
If ($TotalItemSize -match "\((?<Size>.*) ")
{
$Value = $Matches.Size.Replace(",","")
}
If ($Value -gt 50gb)
{
write-host "Mailbox is greater than 50GB for $termUserPrincipalName"
}
else
{
write-host "Proceeding to convert mailbox ..."
Set-Mailbox $termUserPrincipalName -Type shared
}
The code works really well most of the time, but with some mailboxes it falsely reads them as greater than 50GB when they are not. I cannot work out why.
Here is my data in excel which for some reason pasted as an image.
Just an update to this one.
I've been using this and it works great.
$TotalItemSize = Get-MailboxStatistics $UPN | Format-Table TotalItemSize -hidetableheaders | Out-String
$Value = $TotalItemSize.Split("(")[1].Split(" ")[0].Replace(",","")
if ($TotalItemSize -match "\((?<Size>.*) "){
$Value = $Matches.Size.Replace(",","")
$TaotalItemSize = [int64]::Parse($Value)
}
if ($TotalItemSize -gt 50gb){
write-host "Mailbox is greater than 50GB for $UPN"
}
else{
write-host "Proceeding to convert to Shared Mailbox"
}
I would like to write a Power Shell script that would do the following:
- If the user is member of (Domain admins) get me the last 30 days history logon of this user in any Domain joined computer.
I created something now but it still lacks a lot as it reads the security events on the Domain controller and brings the users,time and matches them with the Domain admin group as in the attached screenshot
I would appreciate if someone can help me evolve this script into something useful
$Rusers = Get-WinEvent -Computer dc02 -FilterHashtable #{Logname='Security';ID=4672} -MaxEvents 50 |
` select #{N='User';E={$_.Properties[1].Value}},TimeCreated
$DAUsers = Get-ADGroupMember -Identity "Domain Admins"
Foreach ($DAUser in $DAUsers){
$DomainUser = $DAUser.SamAccountName
foreach ($Ruser in $Rusers){
$RAUser = $Ruser.User
If ($RAUser -match $DomainUser){
Write-Host $Ruser is domain admin }
}[![enter image description here][1]][1]
}
# Get domain admin user list
$DomainAdminList = Get-ADGroupMember -Identity 'Domain Admins'
# Get all Domain Controller names
$DomainControllers = Get-ADDomainController -Filter * | Sort-Object HostName
# EventID
$EventID = '4672'
#
# Get only last 24hrs
$Date = (Get-Date).AddDays(-1)
# Limit log event search for testing as this will take a LONG time on most domains
# For normal running, this will have to be set to zero
$MaxEvent = 50
# Loop through Dcs
$DALogEvents = $DomainControllers | ForEach-Object {
$CurDC = $_.HostName
Write-Host "`nSearching $CurDC logs..."
Get-WinEvent -Computer $CurDC -FilterHashtable #{Logname='Security';ID=$EventID;StartTime = $Date} -MaxEvents $MaxEvent |`
Where-Object { $_.Properties[1].Value -in $DomainAdminList.SamAccountName } |`
ForEach-Object {
[pscustomobject]#{SamAccountName = $_.Properties[1].Value;Time = $_.TimeCreated;LogonEventLocation = $CurDC}
}
}
All the Domain Admin logon events should now be in $DALogEvents
You'll need to group results by name, then export to a file
Thanks a lot for your help, I apologize I was not clear enough. The kind of information I am looking for is pertaining to users who have been utilized for services e.g. (SQL reporting Services, Or Sccm Service ..etc )
This script does what I want but it doesn't run only for domain admin users, it runs for everyone basically and not sure if there's a limit to the time/date.
Is it possible to adjust it to let it run against Domain Admin users for 30 days and print information like. Source IP, User, Target Dc, Date?
Get-EventLog -LogName Security -InstanceId 4624 |
ForEach-Object {
# translate the raw data into a new object
[PSCustomObject]#{
Time = $_.TimeGenerated
User = "{0}\{1}" -f $_.ReplacementStrings[5], $_.ReplacementStrings[6]
Type = $_.ReplacementStrings[10]
"Source Network Address" = $_.ReplacementStrings[18]
Target = $_.ReplacementStrings[19]
}
}
I've added couple more of custom objects to get the result that I needed. I think turning this into a function would be great tool to use for auditing.
Thanks a lot to you #Specialist
# Get domain admin user list
$DomainAdminList = Get-ADGroupMember -Identity 'Domain Admins'
# Get all Domain Controller names
$DomainControllers = Get-ADDomainController -Filter * | Sort-Object HostName
# EventID
$EventID = '4624'
#
# Get only last 24hrs
$Date = (Get-Date).AddDays(-3)
# Limit log event search for testing as this will take a LONG time on most domains
# For normal running, this will have to be set to zero
$MaxEvent = 100
# Loop through Dcs
$DALogEvents = $DomainControllers | ForEach-Object {
$CurDC = $_.HostName
Write-Host "`nSearching $CurDC logs..."
Get-WinEvent -ComputerName $CurDC -FilterHashtable #{Logname='Security';ID=$EventID;StartTime = $Date} -MaxEvents $MaxEvent |`
Where-Object { $_.Properties[5].Value -in $DomainAdminList.SamAccountName } |`
ForEach-Object {
[pscustomobject]#{SourceIP = $_.Properties[18].Value; SamAccountName = $_.Properties[5].Value;Time = $_.TimeCreated;LogonEventLocation = $CurDC}
}
}
$DALogEvents
I have used a script to get all users that have activesync enabled and list all of the connections. Many users have multiple entries where they have used a phone and upgraded, or re-enabled after a wipe.
I am looking to get rid of any entry above 30 days, only for users in a specific OU, or text file full of users.
I believe this code will work universally across the domain:
$DevicesToRemove = Get-ActiveSyncDevice -result unlimited | Get-ActiveSyncDeviceStatistics | where {$_.LastSuccessSync -le (Get-Date).AddDays("-30")}
$DevicesToRemove | foreach-object {Remove-ActiveSyncDevice ([string]$_.Guid) -confirm:$false}
but I only want to do it for either an OU, or txt list.
I can create a .txt list of either the UPN, or the username, which may be easier than looking for all users in an OU. How would I modify that code (or altogether better code?) to remove 30 day+ activesync connections for that txt list?
Text file option would be preferred for a better target.
I think I self answered, so posting for others.
“==============================================================”
“Start Mailbox Retrieve”
“==============================================================”
$mbx = get-casmailbox -resultsize unlimited | where {$_.activesyncenabled -eq $true} ;
“==============================================================”
“End Mailbox Retrieve”
“==============================================================”
$mbx | foreach {
“Processing: “+$_.name
$name = $_.name;
$device = get-activesyncdevicestatistics -mailbox $_.identity | where {$_.LastSuccessSync -le (Get-Date).AddDays(“-30”)};
if($device){
{
”
Device: “+$dev.DeviceType
$csvRows += $dev
}
}
}
“==============================================================”
“Start CSV Write”
“==============================================================”
$csvRows | Export-Csv “c:\ps\staledevices.csv” -NoType
“==============================================================”
“End CSV Write”
“==============================================================”
From http://techtalklive.org/ttlblog/removing-stale-activesync-devices/
Then to remove:
Import-Csv c:\ps\staledevices.csv |foreach {remove-activesyncdevice -identity $_.guid -confirm:$false}
From http://techtalklive.org/ttlblog/removing-stale-activesync-devices/
I work as system administrator in a company with 300 users.
I am looking for a PowerShell script to get all the groups, users in each group and additional single users located at the local admin group of multiple servers joined to a single domain.
This is what I have but it's for local users only.
# Get local and Groups Users List with Content
function get-localusers {
param(
[Parameter(Mandatory=$true,valuefrompipeline=$true)]
[string]$strComputer)
begin {}
Process {
$Select = "Name","Class" | %{
Invoke-Expression "#{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}"
}
If (Test-Connection $strComputer -Count 2 -Quiet){
$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$Users = $computer.psbase.children | ? {$_.psbase.SchemaClassName -eq "User"}
foreach ($User in $Users) {
$User | Select #{N="ComputerName";E={$strComputer}},#{N="User";E={$_.Name}},Class
}
}
Else {
"" | Select #{N="ComputerName";E={$strComputer}},#{N="User";E={"Not able to Ping"}},Class
}
}
end {}
}
Get-Content "c:\temp\Servers.txt" | get-localusers | Select ComputerName,User | Export-Csv "c:\temp\Local-User_$((get-date).toString('MM-dd-yyyy')).csv" -NTI
This is the output from the script above.
"ComputerName", "User"
"mbptl-ws01","mbadmin"
"mbptl-ws01","Guest"
"mbptl-ws01","sv-dtb-pr"
Please help aggregating by groups ( that show users)
Seems that this is a good start :
https://4sysops.com/archives/create-a-list-of-local-administrators-with-powershell/
looks that this will at least get you the members for several computers