Trying to combine two cmdlets and output to an excel spreadsheet - powershell

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;}

Related

Win Powershell get list of active local users

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;}

Power Shell Output filter

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

Powershell Get-EventLog find event with the matching string in its message

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.

How can I find the 'sub properties' of an object in powershell?

I guess I just don't know the proper name of whatever I'm looking for, but this was probably asked a thousand times before.
I started PowerShell not long ago, and I'm struggling to understand where I can find the 'sub properties'(if you can call it those) of an object.
For instance, I was using the VMware PowerCLI, and was tried to figure out how I can find the IP address of a VM.
So for example, I was using the Get-VM command, and when I piped it into get member, I got the following:
PS C:\Users\eitan.rapaport> get-vm "*VRA*" | gm
TypeName: VMware.VimAutomation.ViCore.Impl.V1.VM.UniversalVirtualMachineImpl
Name MemberType Definition
---- ---------- ----------
ConvertToVersion Method T VersionedObjectInterop.ConvertToVersion[T]()
Equals Method bool Equals(System.Object obj)
GetClient Method VMware.VimAutomation.ViCore.Interop.V1.VIAutomation VIObjectCoreInterop.GetClient()
GetConnectionParameters Method VMware.VimAutomation.ViCore.Interop.V1.VM.RemoteConsoleVMParams RemoteConsoleVMIn..
GetHashCode Method int GetHashCode()
GetType Method type GetType()
IsConvertableTo Method bool VersionedObjectInterop.IsConvertableTo(type type)
LockUpdates Method void ExtensionData.LockUpdates()
ObtainExportLease Method VMware.Vim.ManagedObjectReference ObtainExportLease.ObtainExportLease()
ToString Method string ToString()
UnlockUpdates Method void ExtensionData.UnlockUpdates()
CoresPerSocket Property int CoresPerSocket {get;}
CustomFields Property System.Collections.Generic.IDictionary[string,string] CustomFields {get;}
DatastoreIdList Property string[] DatastoreIdList {get;}
DrsAutomationLevel Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.DrsAutomationLevel] ..
ExtensionData Property System.Object ExtensionData {get;}
Folder Property VMware.VimAutomation.ViCore.Types.V1.Inventory.Folder Folder {get;}
FolderId Property string FolderId {get;}
Guest Property VMware.VimAutomation.ViCore.Types.V1.VM.Guest.VMGuest Guest {get;}
GuestId Property string GuestId {get;}
HAIsolationResponse Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.HAIsolationResponse]..
HardwareVersion Property string HardwareVersion {get;}
HARestartPriority Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.Cluster.HARestartPriority] H..
Id Property string Id {get;}
MemoryGB Property decimal MemoryGB {get;}
MemoryMB Property decimal MemoryMB {get;}
Name Property string Name {get;}
Notes Property string Notes {get;}
NumCpu Property int NumCpu {get;}
PersistentId Property string PersistentId {get;}
PowerState Property VMware.VimAutomation.ViCore.Types.V1.Inventory.PowerState PowerState {get;}
ProvisionedSpaceGB Property decimal ProvisionedSpaceGB {get;}
ResourcePool Property VMware.VimAutomation.ViCore.Types.V1.Inventory.ResourcePool ResourcePool {get;}
ResourcePoolId Property string ResourcePoolId {get;}
Uid Property string Uid {get;}
UsedSpaceGB Property decimal UsedSpaceGB {get;}
VApp Property VMware.VimAutomation.ViCore.Types.V1.Inventory.VApp VApp {get;}
Version Property VMware.VimAutomation.ViCore.Types.V1.VM.VMVersion Version {get;}
VMHost Property VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost VMHost {get;}
VMHostId Property string VMHostId {get;}
VMResourceConfiguration Property VMware.VimAutomation.ViCore.Types.V1.VM.VMResourceConfiguration VMResourceConfigu..
VMSwapfilePolicy Property System.Nullable[VMware.VimAutomation.ViCore.Types.V1.VMSwapfilePolicy] VMSwapfile..
As you can see, nothing mentions anything about IP.
I was researching this online, and have found that I should run the following command:
Get-VM | Select Name, #{N="IP Address";E={#($_.guest.IPAddress[0])}}
Which leads me to my question. How can I find the properties under a certain member/property of a command? How could I research the 'sub properties' of 'guest' in that example?
Okay, found it.
In that instance it would be get-vm "*VRA*" | select -ExpandProperty guest | gm
I've been dealing with this for the last two days, so I figured I'd share my solution:
First, I'm saving the VM object to a variable to make it easy to access without searching every time.
$vm = Get-vm -Name steve
To get all the properties of the VM Object
$vm | Select-Object *
If you just want to get the Name you can access it like this:
$vm.Name
If you want to get the Properties of the Guest Object (which is a property of the VM object):
$vm.Guest | Select-Object *
You can access the Properties of the Guest Object through the VM Object like this:
$vm.Guest.VmName
Want the IP addresses of the guest?
$vmip = $vm.Guest.IPAddress
And, because this took me a while to figure out, if that returns ipv4 and ipv6, and you want to filter out the ipv6:
$vmip = $vm.Guest.IPAddress | ?{$_ -notmatch ':'}
Another method of introspection in PowerShell is to just get the class name and then look it up in the API.
PS C:\> $Files = Get-ChildItem *.* -File
PS C:\> $Files[0].GetType().FullName
System.IO.FileInfo
You can then search for that class with either C# or PowerShell to find the API listing.
You can do a similar thing with the VMWare PowerCLI doc. The "all types" list on the left is a list of all the classes used by the module.

How to retrieve email alias and CN for everyone in an AD group using PowerShell

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