mysqli count user actions and print results - mysqli

Im trying to print the user name and the number of times it was found but i cant seem to get the count to show! I have looked and cant seem to find out how.
$sql = "SELECT user, COUNT(user)
FROM user_stats
GROUP BY user";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$user = $row['user'];
$count = $row['count'];
echo $user
echo $count;
}
Im looking to get
User1 2
User2 3
from a database that is like this
USER
User1
User1
User2
User2
User2
Thanks in advance sorry if its simple.

I have solved it now was simple to do
$count = $row['COUNT(user)'];

Related

Powershell 5.1 if statement result is incorrect

I'm using Powershell 5.1 in constrained language mode with no access to additional modules.
I've created a script to return information from "net user query (username) /domain" that includes an If statement to return results if the end user I'm checking isn't a member of certain groups.
The If statement doesn't appear to be working correctly and I'm not sure where I'm going wrong.
1.
$enduser = read-host "please enter username"
Net user query $enduser /domain
$u = #{}; net user $enduser /domain | ConvertFrom-String -Delimiter '\s{2,}' -PropertyNames Name,
Value | ForEach-Object { $u[$_.Name] = $_.Value }
$globalgroups = $u_.'global group memberships'
if ($globalgroups) -inotlike '$_.EXAMPLEGROUPNAME'
{
write-output "user is not part of EXAMPLEGROUP"
}
I have also tried
2.
if ($globalgroups) -inotlike '*EXAMPLEGROUPNAME*'
{
write-output "user is not part of EXAMPLEGROUP"
}
3. as well as creating new variables
$EXAMPLEGROUP1 = { $u[$_.'global group memberships'] = $_.'EXAMPLEGROUPNAME' }
$EXAMPLEGROUPtest = { $u[$_.'global group memberships'] = $_.'value' }
and changing the if statement to;
if ($globalgroups) -inotlike '$examplegroup1'
{
write-output "user is not part of EXAMPLEGROUP"
}
the #2 snippet of code appears to work for one specific group which always appears as the first result in global group memberships, however if a different group name is added which appears later in the list of global group memberships, it always returns that the user isn't part of the group, even though I can see it there.
What can I change to make this work?
I am not sure why exaclty you are using Net user query. But as far as i can see, you try to make an If statement to return results if the end user you are checking isn't a member of certain groups in Active Directory.
I would rather than using Net user query do something like this:
$enduser = "TestUser"
$examplesgroupname = "Test-Group"
$groupmembership = Get-ADPrincipalGroupMembership $enduser
foreach ($membership in $groupmembership.name) {
if ($membership -ne $examplesgroupname) {
$membership_validated = $true
##statement Is true when user is not member of the examplegroup
} else {
$membership_unvalidated = $false
##statement Is false when user is member of the examplegroup
}
}
Write-Host $membership_validated
If you need to use Net user query for a certain reason, than give a short feedback and i will try to fix your script with Net user query included.

Send Email Poweshell

I have an power shell script as below.
The output of the script will be like this:
Index UserID VirtualProxy SessionID VirtualProxyPrefix
1 Mike.Milbur devf dedff eeee
2 Mark.Green devf dedff eeee
Now, after the below script ends and from the table output, I want to send an email to the userID's. I know to send email manually, but how do I loop through the UserID's and send to everyone in the UserID list.
If some one can please help me that would be greatly appreciated.
Connect-Qlik|Out-Null
[System.Collections.ArrayList]$sessions = #()
foreach ($vp in Get-QlikVirtualProxy) {
foreach ($session in Get-QlikSession -virtualProxyPrefix $vp.prefix) {
$s = [PSCustomObject]#{
Index = "[$($sessions.Count+1)]"
UserId = $session.UserId
VirtualProxy = $vp.description
SessionId = $session.SessionId
VirtualProxyPrefix = $vp.prefix
}
$sessions.Add($s)|Out-Null
}
}
$sessions | Format-Table

How to look for members of a group or object with adsi

The company has an AD structure that I need to search for the groupnames where the user is member.
I do know it should be in the "memberof" attribute for the users, let's just say that is not always correct.
I tried the below code to find the username (or objectname) within the "members" attribute for all of the groups within an OU and then bring back the name of the group.
Unfortunately I think I am missing something.
Reverse search (IE: listing the members of a group) is working, but in my case I do not know the name of the groups. Also I need all of the groups, not just a single.
uname ="*anyoldusername*"
$Searcher = [ADSISearcher]"(member=$uname)"
$Searcher.SearchRoot = [ADSI] "LDAP://mydomainsearchroot"
$Searcher.PageSize = 10000
$result = $Searcher.FindAll().Properties.cn
echo $result
This should do it:
$UserName ="TestUser"
$Searcher = [ADSISearcher]""
$Searcher.SearchRoot = [ADSI]"LDAP://mydomainsearchroot"
$Searcher.Filter = "Name=$UserName"
$UserDN = $Searcher.FindOne().properties.distinguishedname
$Searcher.Filter = "(member:1.2.840.113556.1.4.1941:=$UserDN)"
$Searcher.PageSize = 10000
$result = $Searcher.FindAll().Properties.cn
$result
The first search is to find the DN of the user, since that's required for the filter in the next search. To read more about the "1.2.840.113556.1.4.1941" filter see this documentation.
Oh, and echo is an alias for Write-Output in Powershell, better to use that directly or even omit it entirely since a string or variable on it's own will default to Write-Output anyway as you can see when $result is run at the end.

Changing user properties in powershell

I have a script that creates a user and assigns the password and the user to a group but I need to get 2 check boxes ticked - 'User cannot change password' and 'Password never expires' but for the life of me I cannot find out how to do this.
My script so far is this:-
# Create User and add to IGNITEWEBUSERS Group
$user = $domain
# If more then 15 chars trim to just 15 chars
$user = $user.substring(0, 15)
$user = $user + "_web"
# Generate Random Complex Password
# Generate a password with 2 non-alphanumeric character.
$Length = 10
$Assembly = Add-Type -AssemblyName System.Web
$RandomComplexPassword = [System.Web.Security.Membership]::GeneratePassword($Length,2)
$password = $RandomComplexPassword
$group = 'IGNITEWEBUSERS'
$objOu = [ADSI]"WinNT://$computer"
$objUser = $objOU.Create("User", $user)
$objUser.setpassword($password)
$objUser.SetInfo()
$objUser.description = $domain + " IIS User"
$objUser.SetInfo()
$OBjOU = [ADSI]"WinNT://$computer/$group,group"
$OBjOU.Add("WinNT://$computer/$user")
That works and does what it should do but anyone know how I can set those 2 check boxes?
Various threads suggest something similar to Set-ADUser -CannotChangePassword:$true but am not using Active Directory and this doesn't work.
Your advice appreciated
Paul
Got it figured out this morning:-
$objUser.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
Set the useraccountcontrol property. You can find a list of useraccountcontrol flags here: http://support.microsoft.com/kb/305144
Add the values of the flags you want (NORMAL_ACCOUNT = 512, PASSWD_CANT_CHANGE = 64, DONT_EXPIRE_PASSWORD = 65536) for a total of 66112, and set the property to that number:
$obUser.useraccountcontrol = 66112
BTW, you only need to call the SetInfo() method once at the end, after setting all the properties you want to set.
Use WMI to get the user account:
# Use this filter so WMI doesn't spend forever talking to domain controllers.
$user = Get-WmiObject Win32_UserAccount -Filter ("Domain='{0}' and Name='{1}'" -f $env:ComputerName,$Username)
$user.PasswordChangeable = $false
$user.PasswordExpires = $false
$user.Put()

How can I optimize my PowerShell - LDAP Query?

I have created a script that reads from a CSV (or other dataset, but not posting that side) and creates users in my AD environment.
Basically, whatever dataset is passed into the script will be processed, and then a user will be created if they do not exist. If the user exists in the AD already, then the script skips over the entry. This is a CREATE only script.
It's pretty slow, and I'd like to improve the performance whilst keeping the functionality. Can you give me any tips as to how I can make this perform better?
import-csv "c:\PSScripts\LDAP\ADMigrate.csv" | ForEach-Object {
# Define the User OU
$usersOU = [ADSI] "LDAP://ou=Students, dc=live,dc=tcicollege,dc=edu"
# Check for existing users
$existingUsers = ($usersOU.psbase.children | Where-Object {$_.psBase.schemaClassName -eq "User"} | Select-Object -expand Name)
$userQuery = $existingUsers -contains $_.'AccountName'
if ($userQuery) {
echo $_.'AccountName' " already exists in Directory."
} else {
# Create a new user
$newUser = $usersOU.create("user","cn=" + $_.'AccountName')
# Set Account AttributesAMAccountName
$newUser.Put("sAMAccountName", $_.'AccountName')
$newUser.Put("givenName", $_.'FirstName')
$newUser.Put("employeeID", $_.'StudentID')
$newUser.Put("sn", $_.'LastName')
$newUser.Put("department", $_.'Department')
$newUser.Put("company", $_.'SyStudentID')
$newUser.Put("UserPrincipalName", $_.'AccountName' + "#live.tcicollege.edu")
$newUser.Put("mail", $_.'AccountName' + "#live.tcicollege.edu")
$newUser.Put("displayName", $_.'LastName' + "," + " " + $_.'FirstName')
# First Commit
$newUser.SetInfo()
$newUser.userAccountControl="66048"
$newUser.Put("pwdLastset", -1)
$newUser.SetPassword($_.'Password')
# Final Commit
$newUser.SetInfo()
echo $_.'AccountName' " created successfully."
}
}
Thank you in advance for any help you can offer.
Try the static Exists() method to find if the user exists in the Students OU:
$user = [ADSI]::Exists("LDAP://cn=$($_.AccountName),ou=Students, dc=live,dc=tcicollege,dc=edu")
if(!$user)
{
"create code goes here"
}
The $usersOU value is static so you can take it out, place it before the import-csv command.