I want to get the list of active local users on the windows server. When I do Get-LocalUser, I get following output
Name Enabled Description
---- ------- -----------
DefaultAccount False A user account managed by the system.
Guest False Built-in account for guest access to the computer/domain
labadmin True Built-in account for administering the computer/domain
Test True
WDAGUtilityAccount False A user account managed and used by the system for Windows Defender Application Guard scen...
I tried GetLocalUser -Enabled True and got following error
Get-LocalUser : A parameter cannot be found that matches parameter name 'Enabled'.
At line:1 char:79
+ ... ng = New-Object Text.UTF8Encoding $false; Get-LocalUser -Enabled True
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-LocalUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetLocalUserCommandnon-zero return code
What is the correct parameter to filter out the disabled users?
Get-Help -Name "Get-LocalUser" (also written help get-localuser) will show you that the only available parameters are:
SYNTAX
Get-LocalUser [[-Name] <String[]>] [<CommonParameters>]
Get-LocalUser [[-SID] <SecurityIdentifier[]>] [<CommonParameters>]
And there is no parameter to filter on the enabled users. You need to get the results back, then filter afterwards. From the results in your question, the Enabled column shows you that the user objects probably have a property called Enabled which you can check for the filtering:
$users = Get-LocalUser
$enabledUsers = $users | Where-Object { $_.Enabled }
If you did not know that, or that did not work because the column name is not exactly the same as the property name, you could run $users | Get-Member to see what properties the user objects have, and then look through them for ones to check. Enabled is shown in the result:
TypeName: Microsoft.PowerShell.Commands.LocalUser
Name MemberType Definition
---- ---------- ----------
Clone Method Microsoft.PowerShell.Commands.LocalUser Clone()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
AccountExpires Property System.Nullable[datetime] AccountExpires {get;set;}
Description Property string Description {get;set;}
Enabled Property bool Enabled {get;set;}
FullName Property string FullName {get;set;}
LastLogon Property System.Nullable[datetime] LastLogon {get;set;}
Name Property string Name {get;set;}
ObjectClass Property string ObjectClass {get;set;}
PasswordChangeableDate Property System.Nullable[datetime] PasswordChangeableDate {get;set;}
PasswordExpires Property System.Nullable[datetime] PasswordExpires {get;set;}
PasswordLastSet Property System.Nullable[datetime] PasswordLastSet {get;set;}
PasswordRequired Property bool PasswordRequired {get;set;}
PrincipalSource Property System.Nullable[Microsoft.PowerShell.Commands.PrincipalSource] PrincipalSource {ge...
SID Property System.Security.Principal.SecurityIdentifier SID {get;set;}
UserMayChangePassword Property bool UserMayChangePassword {get;set;}
Related
I'm using the comand Get-AzresourceGroup. The ouput of that command is information about ResourID, Tags, Resource group name etc. of all resource groups in Azure. I want to store in a variable all the names of the resource groups, I do not need the other information. Is there a way I can do that?
Thank you!
Comand Output
From the Get-AzResourceGroup documentation, you can simply reference only the Resource Group Name :
$groups = (Get-AzResourceGroup).ResourceGroupName
Or using the CLI, and extracting from the JSON:
$group = az group list | ConvertFrom-Json
$group | Select-Object -Property Name
Try piping the output from Get-AzResourceGroup to Select-Object and use the -Property parameter to specify the property/properties to select.
$rgs = Get-AzResourceGroup | Select-Object -Property ResourceGroupName
Your will results should look something like this.
$rgs
ResourceGroupName
-----------------
ddo-06212021-1
ddo-06212021-2
ddo-06212021-3
cloud-shell-storage-eastus
If you're unsure what properties are available to select from the results of Get-AzResourceGroup, you can first pipe the output to Get-Member, and view the available properties.
Get-AzResourceGroup | Get-Member
TypeName: Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroup
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Location Property string Location {get;set;}
ManagedBy Property string ManagedBy {get;set;}
ProvisioningState Property string ProvisioningState {get;set;}
ResourceGroupName Property string ResourceGroupName {get;set;}
ResourceId Property string ResourceId {get;set;}
Tags Property hashtable Tags {get;set;}
TagsTable Property string TagsTable {get;}
Links
Select-Object - learn.microsoft.com
Get-Member - learn.microsoft.com
I need to look through eventLog security ID 4648, and find the last time the user connected to the machine.
Currently this is my code:
$Values = invoke-command -ComputerName $ComputerName {Get-EventLog -LogName Security -InstanceID 4648 | Select-Object -ExpandProperty Message| ForEach-Object {if($_.Log -match "$String2"){
$_
Break }}}
$Values
The aim was to go through each log until a log where the message has the previously defined username is found, and then stop going through EventLog and return that log.
This is working well, except its not matching the correct log with the specified string.
Is there a way to improve how the matching works? So it actually finds the correct log with the specified user?
# Fill in the regex for the userName
$userName = "userName"
$Values = #(invoke-command -ComputerName $ComputerName {
Get-EventLog -LogName Security -InstanceID 4648 | Where-Object { $_.message -match $Using:userName } | Select-Object -First 1)
}
Your above sample won't work since message is of type string, therefore it doesn't have a Log property. Since we want $userName to be avaiable for read access on the remote machine we can use the $Using: syntax. To break the pipeline "iteration" I'm using Select-Object -First 1 which will return the first object passing the Where-Objectclause.
Resulting from that $Values points to a collection of (deserialized) objects (using the #() operator) of type:
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Which means you can change the -First parameter to e.g. 10 and sort the result on the client machine:
$Values | sort TimeGenerated -Descending
If you want to know which properties are available you can use:
> $Values | gm
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Name MemberType Definition
---- ---------- ----------
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Diagnostics.EventLogEntry otherEntry), bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetObjectData Method void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
ToString Method string ToString()
Category Property string Category {get;}
CategoryNumber Property int16 CategoryNumber {get;}
Container Property System.ComponentModel.IContainer Container {get;}
Data Property byte[] Data {get;}
EntryType Property System.Diagnostics.EventLogEntryType EntryType {get;}
Index Property int Index {get;}
InstanceId Property long InstanceId {get;}
MachineName Property string MachineName {get;}
Message Property string Message {get;}
ReplacementStrings Property string[] ReplacementStrings {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
Source Property string Source {get;}
TimeGenerated Property datetime TimeGenerated {get;}
TimeWritten Property datetime TimeWritten {get;}
UserName Property string UserName {get;}
EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}
Hope that helps.
I'm new to this forum and I apologize if I may have left anything out.
I'm trying to combine two cmdlets(Get-cdmGroupProfile and get-adgroupmember) and get the results(Get-cdmGroupProfile(returns groups from an application called Centrify ) and Get-adgroupmember(which gets group members from the from the cmdlets exported to an excel spreadsheet.
From what I have read ,not all cmdlets can be accept piped input and that is where the need for calculated properties comes in.
I have done this a couple times before( included script at the very bottom of the posting) where I created a calculated property and
was able to get the exported results in an Excel spreadsheet.
However when I tried the code I used before ,it didn't give me the results I was looking for.
After doing some more research I tried to use the calculated properties as such below and then pass it to the select object.
The script just keeps running and doesn't appear to stop. I removed the result variable that I assigned the foreach loop to and removed it the result from being piped into the excel spreadsheet and noticed the results weren't exactly what I wanted.
I was hoping to maybe find a more efficient way of doing this.
I was able to get it exported to an excel spreadsheet ,but it just shows the results from the array which repeats the values ,but doesn't list them like I would like.
I would like the following script to output the following information below
Zonename AD Linux Group Centrify group
PROD ZONE Group1 Group A
PROD ZONE Group2 Group B
TEST ZONE GROUP5 GROUP D
$list = Import-Csv C:\Users\User1\Desktop\Centrify\Inputpega.csv
$result = foreach($item in $list) {
$adgroupmember = Get-ADGroupMember -Identity $item.Group
$centrifygprofile = Get-CdmGroupProfile -Zone $item.DistinguishedName
Get-CdmGroupProfile -Zone $item.DistinguishedName |%{
Get-ADGroupmember -identity $item.Group
$Properties = #(
#{Name='ZoneName';Expression={$centrifygprofile.Zone}},
#{Name=' Centrify Group';Expression={$centrifygprofile.name}},
#{Name='AD Linux GROUP' ;Expression={$adgroupmember.name}},
)
$result | Export-Csv C:\Users\User1\Desktop\Results\results4.csv -
NoTypeInformation
Results that I'm getting -
ZoneName : {OU=TEST ZONE ,OU=TEST Zone
One,OU=Zones,OU=TEST,DC=TEST,DC=com,OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,
OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,OU=Unix,DC=PRODk,DC=com, OU=PROD
ZONE,OU=PROD Zone One,OU=Zones,OU=PROD,DC=PROD,DC=com...}
Centrify Group : {group1#prod.com, group2#prod.com, group3#prod.com,
group4#prod.com...}
PROD_GROUPS,OU=Zones,OU=PROD,OU=PROD,OU=PROD,DC=PROD,DC=com
AD Linux Group : {group6, group7, group8, group9...
ZoneName : {OU=TEST ZONE ,OU=TEST Zone
One,OU=Zones,OU=TEST,DC=TEST,DC=com,OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,
OU=PROD ZONE,OU=PROD Zone
One,OU=Zones,OU=PROD,DC=PROD,DC=com,OU=Unix,DC=PRODk,DC=com, OU=PROD
ZONE,OU=PROD Zone One,OU=Zones,OU=PROD,DC=PROD,DC=com...}
Centrify Group : {group1#prod.com, group2#prod.com, group3#prod.com,
group4#prod.com...}
PROD_GROUPS,OU=Zones,OU=PROD,OU=PROD,OU=PROD,DC=PROD,DC=com
AD Linux Group : {group6, group7, group8, group9...
This is a script I have used multiple before where I was able to combine multiple commands and export the data I wanted to an excel spreadsheet by using calculated properties.
$list = Import-Csv C:\Users\user\Desktop\dn2.csv
$finalzpa = Foreach($item in $list){
$zonezpa = Get-CdmZpaSetting -Zone $item.DistinguishedName
$zoneset = Get-CdmZone -dn $item.DistinguishedName
Get-CdmZone -Dn $item.DistinguishedName | %{
Get-CdmZpaSetting -Zone $item.DistinguishedName |
Select-Object #{Name='Userenabled';Expression={$zonezpa.UserEnabled}},
#{Name='Provisioning Groups enabled';Expression=
{$zonezpa.GroupEnabled}},
#{Name='ZoneName' ;Expression={$zoneset.Name}},
#{Name='User Source';Expression={$zonezpa.UserSource}},
#{Name='Group Source';Expression={$zonezpa.GroupSource}},
#{Name='Distinguished Name';Expression=
{$item.DistinguishedName}}
}}
$finalzpa | Export-Csv -Append -NoTypeInformation
C:\Users\Desktop\zonesautoinfo.csv
$adgroupmember | gm
TypeName: Microsoft.ActiveDirectory.Management.ADPrincipal
Name MemberType Definition
---- ---------- ----------
Contains Method bool Contains(string propertyName)
Equals Method bool Equals(System.Object obj)
GetEnumerator Method System.Collections.IDictionaryEnumerator
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Item ParameterizedProperty
Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Item(string
propertyName) {get;}
distinguishedName Property System.String distinguishedName
{get;set;}
name Property System.String name {get;}
objectClass Property System.String objectClass {get;set;}
objectGUID Property System.Nullable`1[[System.Guid,
mscorlib, Version=4.0.0.0, Culture=neutral,
objectGUID {get;set;}
SamAccountName Property System.String SamAccountName
{get;set;}
SID Property
System.Security.Principal.SecurityIdentifier SID {get;set;}
$centrifygprofile | gm
TypeName: Centrify.DirectControl.PowerShell.Types.CdmGroupProfile
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
CanonicalName Property string CanonicalName {get;}
Computer Property
Centrify.DirectControl.PowerShell.Types.CdmManagedComputer Computer {get;}
Domain Property string Domain {get;}
Gid Property System.Nullable[long] Gid {get;}
Group Property
Centrify.DirectControl.PowerShell.Types.CdmGroup Group {get;}
IsHierarchical Property bool IsHierarchical {get;}
IsMembershipRequired Property System.Nullable[bool] IsMembershipRequired
{get;}
IsOrphan Property bool IsOrphan {get;}
IsSfu Property bool IsSfu {get;}
Name Property string Name {get;}
PreferredServer Property string PreferredServer {get;}
Zone Property
Centrify.DirectControl.PowerShell.Types.CdmZone Zone {get;}
I am working on the easiest way to copy security settings from one server to another, using Powershell, and I'm curious if it's possible to import and entire group, including it's Description and Members properties?
Below is the script I currently have. It appears that I can access the local Group on the remote server using the ADSI adapter, however the Create command bombs with the following error message
Exception calling "Create" with "2" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At \prdhilfs02\install\Monet\ServerUpgrade\DEVHILWB119\Scripts\LocalUsersAndGroups.ps1:25 char:1+ $objCreate = $cn.Create("Group", $objRemote)
$computerName = "DEVWB89"
$objRemote = [ADSI]("WinNT://$computerName/$groupName")
$cn = [ADSI]"WinNT://localhost"
$cn.Create("Group", $objRemote)
EDIT
So I can accomplish what I want by using the script below. I can use the Group Name and Description from the remote server as well as the group information. However, is there a way to use Powershell to simply add the System.DirectoryServices.DirectoryEntry object, and all it's properties, to the local machine? Also, another drawback, is that I have to hard-code the domain for the Group's users.
$cn = [ADSI]"WinNT://localhost"
$computerName = "DEVWB89"
foreach($groupName in $groupArray)
{
$objRemote = [ADSI]("WinNT://$computerName/$groupName")
$objGroup = $cn.Create("Group", $($objRemote.Name))
$objGroup.setinfo()
$objGroup.description = $objGroup.Description
$objGroup.setinfo()
$Members = #($objRemote.psbase.Invoke("Members"))
$Members | ForEach-Object {$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) + ",";}
$tempArray = $MemberNames -split ","
foreach($member in $tempArray)
{
$objGroup.Add("WinNT://SYMETRA/$member, user")
}
}
This will list out all the members of the groups:
$Members = #($objRemote.psbase.Invoke("Members"))
$Members | ForEach-Object {$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null);}
$MemberNames
More helpful info:
PS C:\Users\YourUser\Desktop> $objAdmin = [ADSI]("WinNT://localhost/Administrator")
PS C:\Users\YourUser\Desktop> $objAdmin | gm
TypeName: System.DirectoryServices.DirectoryEntry
Name MemberType Definition
---- ---------- ----------
ConvertDNWithBinaryToString CodeMethod static string ConvertDNWithBinaryToString(psobject deInstance, psobject dnWithBinaryIns...
ConvertLargeIntegerToInt64 CodeMethod static long ConvertLargeIntegerToInt64(psobject deInstance, psobject largeIntegerInstance)
AutoUnlockInterval Property System.DirectoryServices.PropertyValueCollection AutoUnlockInterval {get;set;}
BadPasswordAttempts Property System.DirectoryServices.PropertyValueCollection BadPasswordAttempts {get;set;}
Description Property System.DirectoryServices.PropertyValueCollection Description {get;set;}
FullName Property System.DirectoryServices.PropertyValueCollection FullName {get;set;}
HomeDirDrive Property System.DirectoryServices.PropertyValueCollection HomeDirDrive {get;set;}
HomeDirectory Property System.DirectoryServices.PropertyValueCollection HomeDirectory {get;set;}
LastLogin Property System.DirectoryServices.PropertyValueCollection LastLogin {get;set;}
LockoutObservationInterval Property System.DirectoryServices.PropertyValueCollection LockoutObservationInterval {get;set;}
LoginHours Property System.DirectoryServices.PropertyValueCollection LoginHours {get;set;}
LoginScript Property System.DirectoryServices.PropertyValueCollection LoginScript {get;set;}
MaxBadPasswordsAllowed Property System.DirectoryServices.PropertyValueCollection MaxBadPasswordsAllowed {get;set;}
MaxPasswordAge Property System.DirectoryServices.PropertyValueCollection MaxPasswordAge {get;set;}
MaxStorage Property System.DirectoryServices.PropertyValueCollection MaxStorage {get;set;}
MinPasswordAge Property System.DirectoryServices.PropertyValueCollection MinPasswordAge {get;set;}
MinPasswordLength Property System.DirectoryServices.PropertyValueCollection MinPasswordLength {get;set;}
Name Property System.DirectoryServices.PropertyValueCollection Name {get;set;}
objectSid Property System.DirectoryServices.PropertyValueCollection objectSid {get;set;}
Parameters Property System.DirectoryServices.PropertyValueCollection Parameters {get;set;}
PasswordAge Property System.DirectoryServices.PropertyValueCollection PasswordAge {get;set;}
PasswordExpired Property System.DirectoryServices.PropertyValueCollection PasswordExpired {get;set;}
PasswordHistoryLength Property System.DirectoryServices.PropertyValueCollection PasswordHistoryLength {get;set;}
PrimaryGroupID Property System.DirectoryServices.PropertyValueCollection PrimaryGroupID {get;set;}
Profile Property System.DirectoryServices.PropertyValueCollection Profile {get;set;}
UserFlags Property System.DirectoryServices.PropertyValueCollection UserFlags {get;set;}
PS C:\Users\YourUser\Desktop> $Members[0].GetType().InvokeMember("FullName", "GetProperty", $null, $Members[0], $null)
Exception calling "InvokeMember" with "5" argument(s): "The specified domain either does not exist or could not be contacted.
"
At line:1 char:1
+ $Members[0].GetType().InvokeMember("FullName", "GetProperty", $null, $Members[0] ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException
PS C:\Users\YourUser\Desktop> $Members[0].GetType().InvokeMember("PasswordAge", "GetProperty", $null, $Members[0], $null)
PS C:\Users\YourUser\Desktop> $Members[0].GetType().InvokeMember("UserFlags", "GetProperty", $null, $Members[0], $null)
I am using PowerShell with the Quest AD cmdlets.
I can use the Get-QADGroupMember cmdlet to get a list of everyone in a given group. So far so good but I would like to get their email alias as well. All that is returned currently is something like:
Name Type DN
---- ---- --
Jane Doe User CN=Jane Doe,OU=Employee,DC=companyname,DC=com
Job Blow User CN=Joe Blow,OU=Employee,DC=companyname,DC=com
I tried using get-qaduser with the -includeallproperties flag but I still only get the above fields returned and I don't know how to get at the returned data which the documentation says is cached on the computer.
Any help would be appreciated.
UPDATE
I ended up using "select" similar to below:
$everyone = Get-QADGroupMember "All employees" | select firstname, lastname, email
And that got everything I needed into an array of hashtables. At that point it is easy to do whatever is needed by iterating through everyone with code like:
for ($i=0; $i -le $everyone .length-1; $i++)
{
write-host $everyone[$i].email
}
Took me forever to find the "." notation for pulling specific values out of the hashtable. I did text parsing and that worked but I knew that couldn't be the right way of doing it and eventually found documentation on the dot notation. I hope documenting that here saves someone else some time!
Are you sure it really doesn't return that information? Have you tried piping the command into Get-Member or Format-List -Force *? PowerShell can be configured to only show a few properties of items and not all which might be the case here.
You can select properties using Select-Object or just select if you konw they are there, even though PowerShell doesn't display them by default:
Some-Command | select Name, Type, DN, SomeOtherProperty
You can see this for example with Get-ChildItem too:
PS Home:\> gci *.ps1
Directory: C:\Users\Joey
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2011-04-27 18:50 169 format.ps1
-a--- 2011-04-26 18:36 1064 Untitled1.ps1
-a--- 2011-04-27 18:41 69 x.ps1
-a--- 2011-04-23 19:58 91 y.ps1
The normal invocation only yields four properties: Mode, LastWriteTime, Length and Name. However, there are plenty more, as Get-Member shows.
PS Home:\> gci *.ps1|gm -MemberType Property
TypeName: System.IO.FileInfo
Name MemberType Definition
---- ---------- ----------
Attributes Property System.IO.FileAttributes Attributes {get;set;}
CreationTime Property System.DateTime CreationTime {get;set;}
CreationTimeUtc Property System.DateTime CreationTimeUtc {get;set;}
Directory Property System.IO.DirectoryInfo Directory {get;}
DirectoryName Property System.String DirectoryName {get;}
Exists Property System.Boolean Exists {get;}
Extension Property System.String Extension {get;}
FullName Property System.String FullName {get;}
IsReadOnly Property System.Boolean IsReadOnly {get;set;}
LastAccessTime Property System.DateTime LastAccessTime {get;set;}
LastAccessTimeUtc Property System.DateTime LastAccessTimeUtc {get;set;}
LastWriteTime Property System.DateTime LastWriteTime {get;set;}
LastWriteTimeUtc Property System.DateTime LastWriteTimeUtc {get;set;}
Length Property System.Int64 Length {get;}
Name Property System.String Name {get;}
Rememember that select-object strips down the object and generates new ones.
So in this example:
$test = get-qaduser atestuser | select-object name
$test will be a PSCustomObject (System.Object) containing only the name.
What do you want do do with the data? Output to the console...to a file?
I would do something like this:
get-qadgroupmember "domain users" | format-table name, displayname, email
Or
get-qadgroupmember "domain users" | select-object name, displayname, email | Export-Csv c:\acsvfile.csv