I must be doing something wrong here results are empty, I tried converting html with PsObject it requires -Append that creates multiple html tables and not suited to send an email, any help appreciated.
Foreach($sender in $senders){
$users=Get-TransportServer|Get-MessageTrackingLog -Start (Get-Date).AddHours(-4) -ResultSize Unlimited -Sender $sender.PrimarySmtpAddress |?{$_.Recipients -notlike "*#domain.us" -and $_.RecipientCount -eq "1" -and $_.RecipientStatus -notlike "*,*" -and $_.eventid -eq 'RECEIVE' }
}
$users | % {
$t = New-Object PSObject -Property #{
Sender = $_.Sender
Receiver = $_.Recipients
Messagesubject=$_.Messagesubject
RecipientCount =$_.RecipientCount
TimeStamp=$_.TimeStamp
}
$outtbl += $t
}
$outtbl
Why do you need $users, $outtbl, or $t?
foreach ( $sender in $senders ) {
Get-TransportServer |
Get-MessageTrackingLog -Start (Get-Date).AddHours(-4) -ResultSize Unlimited -Sender $sender.PrimarySmtpAddress |
Where-Object { ($_.Recipients -notlike "*#domain.us") -and
($_.RecipientCount -eq 1) -and
($_.RecipientStatus -notlike "*,*") -and
($_.eventid -eq 'RECEIVE') } | ForEach-Object {
[PSCustomObject] #{
Sender = $_.Sender
Receipients = $_.Recipients
MessageSubject = $_.MessageSubject
RecipientCount = $_.RecipientCount
TimeStamp = $_.TimeStamp
}
}
}
(Not tested - this is just an example of how to eliminate unnecessary variables and write clearer code.)
This code sample requires PowerShell 3.0 or newer because it uses [PSCustomObject].
This was it
foreach ( $sender in $senders ) {
Get-TransportServer |
Get-MessageTrackingLog -Start (Get-Date).AddHours(-4) -ResultSize Unlimited -Sender $sender.PrimarySmtpAddress |
Where-Object { ($_.Recipients -notlike "*#domain.us") -and
($_.RecipientCount -eq 1) -and
($_.RecipientStatus -notlike "*,*") -and
($_.eventid -eq 'RECEIVE') } | ForEach-Object {
$results += New-Object PSObject -Property #{
Sender = $_.Sender
Receiver = $_.Recipients
MessageSubject = $_.MessageSubject
RecipientCount = $_.RecipientCount
TimeStamp = $_.TimeStamp
}
}
}
$results| ConvertTo-Html -Head $style| Out-File $reportpath
Related
In the below script $recexternal and $recinternal always return zero as if there are some issues with the second block.
However, the first executes successfully and gets correct $i and $e output.
What am I doing wrong?
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
$e = 0;
$i = 0;
$recexternal = 0;
$recinternal = 0;
$array = #("JayanManniath.Nair#contoso.com")
foreach ($user in $array) {
$sender = Get-TransportServer |
Get-MessageTrackingLog -ResultSize Unlimited -Sender $user
$sender | %{
if (($_.Source -eq "SMTP") -and ($_.EventId -eq "SEND")) {$e++}
if (($_.Source -eq "STOREDRIVER") -and ($_.EventId -eq "DELIVER")) {$i++}
}
$recipient = Get-TransportServer |
Get-MessageTrackingLog -ResultSize Unlimited -Recipients $user
$reipient | %{
if (($_.Source -eq "SMTP") -and ($_.EventId -eq "RECEIVE")) {$recexternal++}
if (($_.Source -eq "STOREDRIVER") -and ($_.EventId -eq "DELIVER" )) {$recinternal++}
}
}
Write-Host "$user has sent $i emails internally"
Write-Host "$user has sent $e emails externally"
Write-Host "$user has received $recexternal emails from outside organization"
Write-Host "$user has received $recinternal emails from inside the organization"
Aside from the obvious typo your code has the output placed wrongly,
in case of more than one $user in $array the Write-Host commands
should be placed inside the ForEach.
A Where-Object and ().count instead of
the ForEach-Object (%) and the IFs is possibly more efficient.
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
$array = #("JayanManniath.Nair#contoso.com")
ForEach ($user in $array) {
$sender = Get-TransportServer |
Get-MessageTrackingLog -ResultSize Unlimited -Sender $user
$e = ($sender | Where-Object {($_.Source -eq "SMTP") -and
($_.EventId -eq "SEND")} ).Count
$i = ($sender | Where-Object {($_.Source -eq "STOREDRIVER") -and
($_.EventId -eq "DELIVER")} ).Count
$recipient = Get-TransportServer |
Get-MessageTrackingLog -ResultSize Unlimited -Recipients $user
$recexternal = ($recipient | Where-Object {($_.Source -eq "SMTP") -and
($_.EventId -eq "RECEIVE")} ).Count
$recinternal = ($recipient | Where-Object {($_.Source -eq "STOREDRIVER") -and
($_.EventId -eq "DELIVER")} ).Count
Write-Host "$user has sent $i emails internally"
Write-Host "$user has sent $e emails externally"
Write-Host "$user has received $recexternal emails from outside organization"
Write-Host "$user has received $recinternal emails from inside the organization"
}
I create an empty $array early in my script and later i loop over some stuff and want to add this stuff to my array. This works as intended.
$AspxFiles = gci $path $filter -r | ? { $_.DirectoryName -notlike '*Werkstatt*' -and `
$_.DirectoryName -notlike '*- Kopie*' -and `
$_.DirectoryName -notlike '*.1*' -and `
$_.DirectoryName -notlike '*.0*' -and `
$_.DirectoryName -notlike '*.2*' -and `
$_.Name -notlike '*- Kopie*'
}
$array = #()
foreach ($file in $AspxFiles)
{
$getURL = sls -Path $file.FullName -Pattern $regex -AllMatches | ? { $_ -notlike '*www.w3.org*' -and `
$_ -notlike '*jquery.com*' -and `
$_ -notlike '*www.mwe*' } |
% { $_.Matches } | % { $_.Value }
foreach ($URL in $getURL)
{
$Request = [System.Net.WebRequest]::Create($URL)
$Response = $Request.GetResponse()
$Status = [int]$Response.StatusCode
if ($Status -ne 200 -or $Response.ResponseUri -like '*PageNotFound*')
{
$x = [PSCustomObject] #{
File = $file.Name
URL = $URL
} ; $array += $x
}
$Response.Close()
}
}
But the output of $array is like this:
#{File=B-1.56.aspx; URL=http://sdfsdfsdf/b-1.39.4_fr1_d.pdf}
#{File=B-1.56.aspx; URL=http://sdfsdfsdfssd/b-1.39.4_fr1_d.pdf}
#{File=B-1.58.aspx; URL=https://sdfffssd/b-1.39.6_de_d.pdf}
#{File=B-1.58.aspx; URL=https://fsdfsfb-1.39.6_de_d.pdf}
How can I get this formatted like a list so I can grab the File and URL Property to send it as an E-Mail body like this?:
$body = $array | sort File | ConvertTo-Html -Property File,URL -Head "<html><h2>Folgende Links wurden im Katalog nicht gefunden:</h2><br></html>" | Out-String
Looks like this is still only a part of your script but:
I'd transform your anded wildcards into a -notmatch RegEx with OR'ed | entries
and set $array = Foreach($file ... gathering all ouput
$REDir = '.*Werkstatt.*|.*- Kopie.*|.*\.[012].*'
$REURL = '.*www\.w3\.org.*|.*jquery\.com.*|.*www.mwe.*'
$AspxFiles = Get-ChildItem $path $filter -r |
Where-Object { $_.DirectoryName -notmatch $REDir -and `
$_.Name -notlike '*- Kopie*'}
$array = #()
$array = foreach ($file in $AspxFiles) {
$getURL = Select-String -Path $file.FullName -Pattern $regex -AllMatches |
Where-Object { $_ -notmatch $REURL } |
ForEach-Object { $_.Matches } | ForEach-Obkect { $_.Value }
ForEach ($URL in $getURL) {
$Request = [System.Net.WebRequest]::Create($URL)
$Response = $Request.GetResponse()
$Status = [int]$Response.StatusCode
if ($Status -ne 200 -or $Response.ResponseUri -like '*PageNotFound*') {
[PSCustomObject] #{
File = $file.Name
URL = $URL
}
}
$Response.Close()
}
}
$body = $array | Sort-Object File |
ConvertTo-Html -Property File,URL -Head `
"<html><h2>Folgende Links wurden im Katalog nicht gefunden:</h2><br></html>" |
Out-String
I need to make a CSV file with the name of the mailbox (mb Identity), user, accessrights and deny. But I only want to that for ADUsers who have a givenname AND a surname not only a surname.
I thought of something like that:
$File_Path = $args[0]
$File_Path = ((Get-Item -Path ".\" -Verbose).FullName) + "\" + $File_Path
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
[System.IO.File]::WriteAllLines($File_Path, "Mailbox;RightHolder;Rights;Deny", $Utf8NoBomEncoding)
$Mailboxes = Get-Mailbox -ResultSize Unlimited
Foreach ($Mailbox in $Mailboxes) {
$mbPermissions = get-mailboxpermission $Mailbox
$str_DN = $Mailbox.DistinguishedName
$ad_obj = [ADSI]"GC://$str_DN"
Foreach ($mbPermission in $mbPermissions) {
If ($mbPermission.IsInherited -eq $False -and $mbPermission.User -notlike "NT-AUTORITÄT\SELBST") {
[System.IO.File]::AppendAllText($File_Path, "$($mbPermission.Identity);$($mbPermission.User);$($mbPermission.AccessRights);$($mbPermission.Deny)`r", $Utf8NoBomEncoding)
}
}
$ADPermissions = get-ADPermission $Mailbox.Identity
Foreach ($ADPermission in $ADPermissions) {
If ($ADPermission.ExtendedRights -like "Send-As" -and $ADPermission.User -notlike "NT-AUTORITÄT\SELBST" -and $ADPermission.Deny -eq $false) {
[System.IO.File]::AppendAllText($File_Path, "$($ADPermission.Identity);$($ADPermission.User);$($ADPermission.ExtendedRights);$($ADPermission.Deny)`r", $Utf8NoBomEncoding)
}
}
}
This works perfectly fine for creating the csv file with all credentials I need, but it doesn't exclude mailboxes from users who have no givenname. I'm a little bit stuck here.
Thanks for your help!
EDIT:
Solved it! Just put these lines instead of the $Mailboxes part:
$Mailboxes = get-mailbox -ResultSize Unlimited | select -ExpandProperty samaccountname
$Filter = foreach ($Obj in $Mailboxes) { get-aduser $Obj | select -property givenname,samaccountname }
$NoGivenName = $Filter | where { $_.givenname -ne $null } | select -ExpandProperty samaccountname
$BoxesFiltered = foreach ($Box in $NoGivenName) { get-mailbox $Box }
Can you try the following, it may take a little longer as the it has to filter out with a Get-ADUser to regenerate the list.
Import-Module ActiveDirectory
$File_Path = $args[0]
$File_Path = ((Get-Item -Path ".\" -Verbose).FullName) + "\" + $File_Path
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
[System.IO.File]::WriteAllLines($File_Path, "Mailbox;RightHolder;Rights;Deny", $Utf8NoBomEncoding)
$Mailboxes = Get-Mailbox -ResultSize Unlimited
$Mailboxes = Foreach ($Mailbox in $Mailbox){ (get-aduser $mailbox | where { ([string]::IsNullOrEmpty($_.givenname) -eq $false) }).samaccountname }
Foreach ($Mailbox in $Mailboxes)
{
$mbPermissions = get-mailboxpermission $Mailbox
$str_DN = $Mailbox.DistinguishedName
$ad_obj = [ADSI]"GC://$str_DN"
Foreach ($mbPermission in $mbPermissions)
{
If ($mbPermission.IsInherited -eq $False -and $mbPermission.User -notlike "NT-AUTORITÄT\SELBST")
{
[System.IO.File]::AppendAllText($File_Path, "$($mbPermission.Identity);$($mbPermission.User);$($mbPermission.AccessRights);$($mbPermission.Deny)`r", $Utf8NoBomEncoding)
}
}
$ADPermissions = get-ADPermission $Mailbox.Identity
Foreach ($ADPermission in $ADPermissions)
{
If ($ADPermission.ExtendedRights -like "Send-As" -and $ADPermission.User -notlike "NT-AUTORITÄT\SELBST" -and $ADPermission.Deny -eq $false)
{
[System.IO.File]::AppendAllText($File_Path, "$($ADPermission.Identity);$($ADPermission.User);$($ADPermission.ExtendedRights);$($ADPermission.Deny)`r", $Utf8NoBomEncoding)
}
}
}
I want to generate a list of users, with the exception of a list of names. This exclusion list changes from week to week.
$exclude = #('smith, bob', 'jones, tom', ...)
$csvmaster = #()
$uacct = 'User Account'
$UserID = 'User ID'
$lastname = 'Last Name'
... other attributes
$ulist = get-aduser -filter {enabled -eq 'true'} -properties * | ? {$_.Distinguishedname -like '*Standard User*' -and $_.title -ne $null -and $_.employeenumber -ne $null}
foreach ($u in $ulist)
{
if ($u.name -notmatch $exclude) {
$csvline = New-Object System.Object
$csvline | Add-Member -MemberType NoteProperty -name $UserID -value $u.EmployeeNumber
$csvline | Add-Member -MemberType NoteProperty -name $lastname -value $u.surname
...other attributes
$csvmaster += $csvline
}
}
...Output to csv
When I run this, the names I want to exclude still make it into the list. I also tried -notcontains and excluding them like this:
$ulist = get-aduser -filter {enabled -eq 'true'} -properties * | ? {$_.Distinguishedname -like '*Standard User*' -and $_.title -ne $null -and $_.employeenumber -ne $null -and $_.name -notmatch $exclude}
This behaves the same way.
Cheers.
So I think my problem was the way Get-ADUser accepts input value. And/Or my logic in general. I changed the code to this:
$exclude = #( ..list..of..names..)
$csvline = #()
$ulist = get-aduser ...
foreach ($u in $ulist)
{
if ($exclude -notcontains $u.name)
{
...
$csvline += $u.name
}
}
And it is doing what I need.
I have a script that works great but I would like to only export the machines that meet one of the three conditions in the foreach statement. Right now it exports all the machines, which I have to clean up manually in excel.
#Create an LDAP searcher object and pass in the DN of the domain we wish to query
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"LDAP://DC=ten,DC=thomsonreuters,DC=com")
#Pass in the ceriteria we are searching for.
#In this case we're looking for computers that are enabled and running Windows 7
$Searcher.Filter = "(&(objectCategory=computer)(objectClass=computer)(!UserAccountControl:1.2.840.113556.1.4.803:=2)(operatingSystem=Windows 7*))"
$Searcher.PageSize = 100000
# Populate General Sheet(1) with information
$results = $Searcher.Findall()
$results | ForEach-Object { $_.GetDirectoryEntry() } |
select #{ n = 'CN'; e = { ($_.CN) } },
#{ n = 'DistinguishedName'; e = { $_.DistinguishedName } },
#{ n = 'extensionattribute7'; e = { $_.extensionattribute7 } },
#{ n = 'extensionattribute1'; e = { $_.extensionattribute1 } },
#{ n = 'NewComputerName'; e = { 'Filler' } } |
Export-Csv 'C:\temp\Windows7_Only.csv' -NoType -Force
$csv = Import-Csv -Path "c:\Temp\Windows7_Only.csv"
foreach ($row in $csv)
{
if (($row.CN -notmatch '^U\d{7}') -and ($row.DistinguishedName -like "*Laptops*") -and ($row.extensionattribute7 -match '^U\d{7}$') -and ($row.CN -notmatch '\d{3}'))
{
$row.NewComputerName = $row.extensionattribute7 + "-TPL-ZZ"
}
elseif (($row.CN -notmatch '^U\d{7}') -and ($row.DistinguishedName -like "*Desktops*") -and ($row.extensionattribute7 -match '^U\d{7}$') -and ($row.CN -notmatch '\d{3}'))
{
$row.NewComputerName = $row.extensionattribute7 + "-TPD-ZZ"
}
elseif (($row.CN -notmatch '^U\d{7}') -and ($row.DistinguishedName -like "*Virtual*") -and ($row.extensionattribute7 -match '^U\d{7}$') -and ($row.CN -notmatch '\d{3}'))
{
$row.NewComputerName = $row.extensionattribute7 + "-TPV-ZZ"
}
}
$csv | export-csv c:\temp\fixed.csv -NoTypeInformation -Force
Try this:
$csv = $csv | where { ($_.CN -notmatch '^U\d{7}') -and ($_.CN -notmatch '\d{3}') -and ($_.extensionattribute7 -match '^U\d{7}$') -and (($_.DistinguishedName -like "*Laptops*") -or ($_.DistinguishedName -like "*Desktops*") -or ($_.DistinguishedName -like "*Virtual*")) }
Before the final line. It should filter out any ones that haven't met any of the criteria in the foreach loop