Is it possible to get current users AD attributes without Get-ADUser?
Am new to powershell. I need to get few attributes like title, email & department for user.
I tried use :
get-wmiobject -Class win32_useraccount -Filter "name='John.Doe'" | select *
PSComputerName : NY-Z343
Status : OK
Caption : BEAZL-INC\john.doe
PasswordExpires : False
__GENUS : 2
__CLASS : Win32_UserAccount
__SUPERCLASS : Win32_Account
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
__PROPERTY_COUNT : 16
__DERIVATION : {Win32_Account, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : NY-Z343
__NAMESPACE : rootcimv2
__PATH : \BEAZL-INCrootcimv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
AccountType : 512
Description : Dude account for gaming
Disabled : False
Domain : BEAZL-INC
FullName : John Doe
InstallDate :
LocalAccount : False
Lockout : False
Name : john.doe
PasswordChangeable : True
PasswordRequired : False
SID : S-1-5-21-3384058-193304-10174538-501
SIDType : 1
Scope : System.Management.ManagementScope
Path : \\NY-Z343\root\clmv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
Options : System.Management.ObjectGetOptions
ClassPath : \\NY-Z34\root\clmv2:Win32_UserAccount
Properties : {AccountType, Caption, Description, Disabled...}
SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers : {dynamic, Locale, provider, UUID}
Site :
Container :
Yes, you can use [adsisearcher], which is a type accelerator for .NET's DirectorySearcher class. This doesn't require installing anything additional.
Here's an example that will search for a user by the name attribute and return the title, mail, and department attributes:
# This is the search filter
$searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person)(name=John.Doe))"
# List all the propterties you want to use
$searcher.PropertiesToLoad.AddRange(#("title", "mail", "department"))
# By default, it will search the same domain as the logged in user.
# If you need to search a different domain, uncomment and edit this line.
# $searcher.SearchRoot = [adsi]"LDAP://example.com"
$user = $searcher.FindOne()
$title = $user.Properties["title"][0]
Related
While recently working with the native Powershell DNS commandlets, specifically Get-DNSServerResourceRecord, I noticed something strange that does not make sense to me.
When I look into my zone using native DNS tools, LDAP query tools, or even ADSIedit, I see only a single DNS object representing a given hostname.
However, when I do the same with Powershell, I instead get two objects for a given host, one for the NETBIOS name, and the other for the FQDN. All other attributes are the same, including the IP.
For example, if I had a computer named computer1: This is what I see.
PS C:\> Get-DnsServerResourceRecord -ZoneName 'mydomain.local' -RRType A -ComputerName 'DNSServer1' | Where-Object {$_.hostname -like "Computer1*"} | fl *
DistinguishedName : DC=computer1.mydomain.local,DC=mydomain.local,cn=MicrosoftDNS,DC=DomainDnsZones,DC=mydomain,DC=local
HostName : COMPUTER1.mydomain.local
RecordClass : IN
RecordData : DnsServerResourceRecordA
RecordType : A
Timestamp :
TimeToLive : 01:00:00
Type : 1
PSComputerName :
CimClass : root/Microsoft/Windows/DNS:DnsServerResourceRecord
CimInstanceProperties : {DistinguishedName, HostName, RecordClass, RecordData...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
DistinguishedName : DC=computer1,DC=mydomain.local,cn=MicrosoftDNS,DC=DomainDnsZones,dc=mydomain,dc=local
HostName : COMPUTER1
RecordClass : IN
RecordData : DnsServerResourceRecordA
RecordType : A
Timestamp :
TimeToLive : 01:00:00
Type : 1
PSComputerName :
CimClass : root/Microsoft/Windows/DNS:DnsServerResourceRecord
CimInstanceProperties : {DistinguishedName, HostName, RecordClass, RecordData...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
I'm so confused at why Powershell is showing this and where it's actually pulling it from. I cannot locate those FQDN objects using native LDAP tools, even ADFind.
Is this some weird artifact/bug of the Powershell DNS cmdlets? Or does DNS records store dual entries for a given host, but only display one using native tools?
Neither make sense to me, as I would not expect a cmdlet to just make up DN values on the fly, and this doesn't occur for all host records.The latter does not seem possible as this is not occurring for all records in the zone. I have about 100 more records without the fqdn than with (10926 vs 10824).
EDIT If it helps, here is an ADFind query for the same object (and wildcard).
C:\temp>adfind -h dnsserver1 -domaindns -f "(&(name=computer1*))" name
AdFind V01.57.00cpp Joe Richards (support#joeware.net) November 2021
Using server: dnsserver1.mydomain.local:389
Directory: Windows Server 2016
Base DN: DC=DomainDnsZones,DC=ad,DC=ewsad,DC=net
dn:DC=computer1,DC=mydomain.local,CN=MicrosoftDNS,DC=DomainDnsZones,DC=mydomain,DC=local
>name: computer1
1 Objects returned
I can confirm this behavior.
In powershell, this returns 2 results for many of the computers (maybe all, I didn't check)
Get-DnsServerResourceRecord -ZoneName 'domain.com' -RRType A -ComputerName dnserver1 | where hostname -like Computer1*
DistinguishedName : DC=Computer1.domain.com,DC=domain.com,cn=MicrosoftDNS,DC=DomainDnsZones,DC=domain,DC=com
HostName : Computer1.domain.com
RecordClass : IN
RecordData : DnsServerResourceRecordA
RecordType : A
Timestamp : 12/8/2022 9:00:00 AM
TimeToLive : 00:20:00
Type : 1
PSComputerName :
CimClass : root/Microsoft/Windows/DNS:DnsServerResourceRecord
CimInstanceProperties : {DistinguishedName, HostName, RecordClass, RecordData...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
DistinguishedName : DC=Computer1,DC=domain.com,cn=MicrosoftDNS,DC=DomainDnsZones,DC=domain,DC=com
HostName : Computer1
RecordClass : IN
RecordData : DnsServerResourceRecordA
RecordType : A
Timestamp : 12/8/2022 9:00:00 AM
TimeToLive : 00:20:00
Type : 1
PSComputerName :
CimClass : root/Microsoft/Windows/DNS:DnsServerResourceRecord
CimInstanceProperties : {DistinguishedName, HostName, RecordClass, RecordData...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
But a dsquery results in one record.
dsquery computer -name computer1* -s dnsserver1
"CN=Computer1,OU=Computers,DC=domain,DC=com"
You can confirm only one of these is a real AD object.
$recordlist = Get-DnsServerResourceRecord -ZoneName 'domain.com' -RRType A -ComputerName dnserver1 | where hostname -like Computer1*
foreach($record in $recordlist){
Write-Host "Checking DN $($record.DistinguishedName)" -ForegroundColor Cyan
$found = $record.DistinguishedName |
Get-ADObject -ErrorAction SilentlyContinue
if($found){
Write-Host "Record found in AD" -ForegroundColor Green
}
else{
Write-Host "Record not in AD" -ForegroundColor DarkGray
}
}
So I must conclude thus far the evidence does indicate the Get-DnsServerResourceRecord is adding a duplicated record with the FQDN as well. Hopefully someone can find or knows why it was implemented in this manner.
I am trying to get all camera devices ID and respective names using PowerShell command line. I tried several commands, but nothing has done what I am aiming. Below my "best" approach:
Get-CimInstance Win32_PnPEntity | where caption -match 'camera'
output
Caption : Remote Desktop Camera Bus
Description : UMBus Enumerator
InstallDate :
Name : Remote Desktop Camera Bus
Status : OK
Availability :
ConfigManagerErrorCode : 0
ConfigManagerUserConfig : False
CreationClassName : Win32_PnPEntity
DeviceID : UMB\UMB\1&841921D&0&RDCAMERA_BUS
ErrorCleared :
ErrorDescription :
LastErrorCode :
PNPDeviceID : UMB\UMB\1&841921D&0&RDCAMERA_BUS
PowerManagementCapabilities :
PowerManagementSupported :
StatusInfo :
SystemCreationClassName : Win32_ComputerSystem
SystemName : DESKTOP
ClassGuid : {4d36e97d-e325-11ce-bfc1-08002be10318}
CompatibleID :
HardwareID : {UMB\UMBUS}
Manufacturer : Microsoft
PNPClass : System
Present : True
Service : umbus
PSComputerName :
I know, for example, that generally the integrated camera has a name "integrated camera" with a ID "0". But this is not what is being shown.
Get-CimInstance Win32_PnPEntity | ? { $_.service -eq "usbvideo" } | Select-Object -Property PNPDeviceID, Name
I try to automatically copy files from MTP-Devices (Smartphones) to my PC. I took several little code snippets from the internet for that and a lot of trial and error (several days), because I have no idea about powershell. But now everything works fine so far. The only problem is, that I have to manually put the name in for a device in my script, every time I took an other device. So I'm searching for a solution to automatically get the name from the actual device and save it in a variable.
I have tried this code:
Get-WmiObject -class win32_pnpentity -computername localhost | where-object {$_.HardwareID -like "*MTP*"} | format-list
As result i get:
__GENUS : 2
__CLASS : Win32_PnPEntity
__SUPERCLASS : CIM_LogicalDevice
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_PnPEntity.DeviceID="USB\\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_ANDROID\\6&5F679FC&0
&0000"
__PROPERTY_COUNT : 26
__DERIVATION : {CIM_LogicalDevice, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : EXO-SURFACE
__NAMESPACE : root\cimv2
__PATH : \\EXO-SURFACE\root\cimv2:Win32_PnPEntity.DeviceID="USB\\VID_04E8&PID_6860&MS_COMP_MTP&SAM
SUNG_ANDROID\\6&5F679FC&0&0000"
Availability :
Caption : Galaxy S9+
ClassGuid : {eec5ad98-8080-425f-922a-dabf3de3f69a}
CompatibleID : {USB\MS_COMP_MTP, USB\Class_06&SubClass_01&Prot_01, USB\Class_06&SubClass_01,
USB\Class_06...}
ConfigManagerErrorCode : 0
ConfigManagerUserConfig : False
CreationClassName : Win32_PnPEntity
Description : SM-G965F
DeviceID : USB\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_ANDROID\6&5F679FC&0&0000
ErrorCleared :
ErrorDescription :
HardwareID : {USB\VID_04E8&PID_6860&REV_0400&MS_COMP_MTP&SAMSUNG_Android,
USB\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_Android,
USB\SAMSUNG_MOBILE&MS_COMP_MTP&SAMSUNG_Android, USB\SAMSUNG_MOBILE&MI_00...}
InstallDate :
LastErrorCode :
Manufacturer : Samsung Electronics Co., Ltd.
Name : Galaxy S9+
PNPClass : WPD
PNPDeviceID : USB\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_ANDROID\6&5F679FC&0&0000
PowerManagementCapabilities :
PowerManagementSupported :
Present : True
Service : WUDFWpdMtp
Status : OK
StatusInfo :
SystemCreationClassName : Win32_ComputerSystem
SystemName : EXO-SURFACE
PSComputerName : EXO-SURFACE
This looks very fine, because for the Name it's recognized as "Galaxy S9+" like it should. So do anyone here know, how to extract this Device Name into an variable? I would be very thankful, because I am a real noob in powershell and it's a project to help my parents, who have their problems with technology.
I'm new to powershell and I"m trying to get just the IPv4 address of a vm and save it as a string.
I can get all network attributes like so:
PS C:\Windows\system32> get-vm | select -ExpandProperty networkadapters | select vmname, macaddress, switchname, ipaddres
sses
VMName MacAddress SwitchName IPAddresses
------ ---------- ---------- -----------
foobar vSwitch {192.0.2.1, fe80::84a...
I can get both the v4 and the v6 ip address
PS C:\Windows\system32> $IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses
PS C:\Windows\system32> $IP
192.0.2.1
fe80::d47e:
----------
How can I get just the v4 address as a string?
Update
It looks like there is no object property that just includes the v4 address
PS C:\Windows\system32> GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter | Format-List -Property *
IovWeight : 0
IovQueuePairsRequested : 1
IovQueuePairsAssigned : 0
IovInterruptModeration : Default
IovUsage : 0
ClusterMonitored : True
VirtualFunction :
IsLegacy : False
IsManagementOs : False
IsExternalAdapter : False
Id : Microsoft:xxxxxxxxxxx
AdapterId : xxxxxxxxxxx
DynamicMacAddressEnabled : True
MacAddress : 00155D5B9B14
MacAddressSpoofing : Off
SwitchId : xxxxxxxxxxx
Connected : True
PoolName :
SwitchName : vSwitch
AclList : {}
ExtendedAclList : {}
IsolationSetting : Microsoft.HyperV.PowerShell.VMNetworkAdapterIsolationSetting
CurrentIsolationMode : Vlan
RoutingDomainList : {}
DhcpGuard : Off
RouterGuard : Off
PortMirroringMode : None
IeeePriorityTag : Off
VirtualSubnetId : 0
DynamicIPAddressLimit : 0
StormLimit : 0
AllowTeaming : Off
VMQWeight : 100
IPsecOffloadMaxSA : 512
VmqUsage : 0
IPsecOffloadSAUsage : 0
VFDataPathActive : False
VMQueue :
MandatoryFeatureId : {}
MandatoryFeatureName : {}
VlanSetting : Microsoft.HyperV.PowerShell.VMNetworkAdapterVlanSetting
BandwidthSetting :
BandwidthPercentage : 0
TestReplicaPoolName :
TestReplicaSwitchName :
StatusDescription : {OK}
Status : {Ok}
IPAddresses : {192.0.2.1, fe80::xxxxxxxxxxx}
ComputerName : xxxxxxxxxxx
Name : Network Adapter
IsDeleted : False
VMId : xxxxxxxxxxx
VMName : foobar
VMSnapshotId : 00000000-0000-0000-0000-000000000000
VMSnapshotName :
Key :
You can just filter out any IP that has ":" in it, as such:
$IP | ?{$_ -notmatch ':'}
Assuming there is only 1 V4 address, and that the v4 address is the first output, do:
$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses | Select-String -List 1
IPAddresses looks like an array or list and you only want the first one so try:
$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses[0]
I have configured the EventForwarding Manually but I was wondeing If I could do it programmatically and I came across the Group Policy Cmdlets which seems to be the solution. Here is what I am trying to configure manually in the image below.
When I run the Get-GPO -all cmdlet I don't see any GPOs related to Event Forwarding. However when I ran the Get-GPResultantSetOfPolicy with the specified path of an XML file, I got to see my configuration of the Subscription manager of the Event Forwarding.
Question 1: Why isn't the event forwarding policy shown in Get-GPO -all result?
Question 2: How to find out the GUID of the policy I need so I can use the Get-GPRegistryValue? besides providing the Key (which I was able to find and verfiy that it has my configuration that I have done through the gpedit.msc UI.
Question 3: How to figure out the display name of the policy in question? I tried the following:
PS C:\Windows\PolicyDefinitions> Get-GPRegistryValue -Name SubscriptionManager -Key HKEY_LOCAL_MACHINE\SOFTWARE\Policies
\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
Where I tried for the Name attribute different things like : "EventForwarding", "EventForward", "SubscriptionManager" and even "Configure target Subscription Manager".
And here is what I got :
***Get-GPRegistryValue : The command cannot be completed because a GPO that is named "SubscriptionManager" was not found
in the nfstest.stbtest.microsoft.com domain. Make sure that the GPO that is specified by the Name parameter exists in
the domain that is specified for the cmdlet. Then, run the command again.
Parameter name: Name
At line:1 char:1
+ Get-GPRegistryValue -Name SubscriptionManager -Key HKEY_LOCAL_MACHINE\SOFTWARE\P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Microsoft.Group...tryValueCommand:GetGPRegistryValueCommand) [Get-GPReg
istryValue], ArgumentException
+ FullyQualifiedErrorId : GpoWithNameNotFound,Microsoft.GroupPolicy.Commands.GetGPRegistryValueCommand***
Any Help regarding any of the three related questions would be appreciated.
EDIT 1:
As you can see in the image below, when I manually configure taregt subscription manager, I get the key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager in the registry. My question for now is simple, how can I do that with cmdlets? All what I tried so far didn't create that key for me in the registry , NOT the AD.
Thanks
Sorry not sure to understand what you do. Here is a full example :
PS C:\silogix> Import-Module grouppolicy
PS C:\silogix> New-GPO -Name "MyGPO" | New-GPLink -target "OU=SousMonou,OU=MonOu,DC=dom,DC=fr" `
-linkenabled yes
GpoId : f31df409-ca35-47cd-b699-52426e2bd196
DisplayName : MyGPO
Enabled : True
Enforced : False
Target : OU=SousMonou,OU=MonOu,DC=dom,DC=fr
Order : 1
PS C:\silogix> get-gpo -all
DisplayName : Default Domain Policy
DomainName : dom.fr
Owner : DOM\Admins du domaine
Id : 31b2f340-016d-11d2-945f-00c04fb984f9
GpoStatus : AllSettingsEnabled
Description :
CreationTime : 16/09/2010 21:07:03
ModificationTime : 09/09/2011 21:04:06
UserVersion : AD Version: 0, SysVol Version: 0
ComputerVersion : AD Version: 11, SysVol Version: 11
WmiFilter :
DisplayName : Default Domain Controllers Policy
DomainName : dom.fr
Owner : DOM\Admins du domaine
Id : 6ac1786c-016f-11d2-945f-00c04fb984f9
GpoStatus : AllSettingsEnabled
Description :
CreationTime : 16/09/2010 21:07:03
ModificationTime : 06/06/2012 17:58:00
UserVersion : AD Version: 0, SysVol Version: 0
ComputerVersion : AD Version: 4, SysVol Version: 4
WmiFilter :
DisplayName : MyGPO
DomainName : dom.fr
Owner : DOM\Admins du domaine
Id : f31df409-ca35-47cd-b699-52426e2bd196
GpoStatus : AllSettingsEnabled
Description :
CreationTime : 08/06/2012 07:04:16
ModificationTime : 08/06/2012 07:04:16
UserVersion : AD Version: 0, SysVol Version: 0
ComputerVersion : AD Version: 0, SysVol Version: 0
PS C:\silogix> Set-GPRegistryValue -Name "MyGPO" -Key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager -value "Server=https://EVTCPT:5986/wsman/SubscriptionManager/WEC" -t
ype String
PS C:\silogix> Get-GPRegistryValue -name "MyGPO" -Key "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager"
KeyPath : SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
FullKeyPath : HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
Hive : LocalMachine
PolicyState : Set
Value : Server=https://EVTCPT:5986/wsman/SubscriptionManager/WEC
Type : String
ValueName : 1
HasValue : True
So you can see it in GPMC.MSC.