Search This Blog

Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Jan 31, 2024

[PowerShell] When ExpandProperty is not good enough

The ExpandProperty parameter in select-object cmdlet is useful to view full values of a compound property (e.g. when a property's value is an array or an object). However the limitation is also obvious. It accepts only one property, so we are forced to write a script block to process all results, using a different way to convert/expand properties one by one, before we can finally assembly the output.

The other way to do it is to use inline expression. See below

$targetedProperties=@(
    samaccountname,
    @{l='membership'; e={$_.memberof}}
    @{l='allEmailAddresses'; e={$_.proxyAddresses}}
$uObj = get-aduser 'johnDoe' -properties *
$expandedObj = $uObj | select $targetedProperties
 



Array that includes most meaningful AD attributes for admins


$meaningfulP = @(
    "AccountExpirationDate"
    #"accountExpires" # above converted value is readable to human - blank means never
    "AccountLockoutTime"
    "AccountNotDelegated"
    "AllowReversiblePasswordEncryption"
    #"BadLogonCount" # these are temporary values that are reset by AD periodically
    #"badPasswordTime"
    #"badPwdCount"
    "c"
    "CannotChangePassword"
    "CanonicalName"
    "City"
    "CN"
    "co"
    "codePage"
    "Company"
    "Country"
    "countryCode"
    "Created"
    "createTimeStamp"
    "Deleted"
    "Department"
    #"departmentNumber"
    @{l="deptNumber";e={$_.departmentNumber}}
    "Description"
    "DisplayName"
    "DistinguishedName"
    "Division"
    "EmailAddress"
    "EmployeeID"
    "EmployeeNumber"
    "employeeType"
    "Enabled"
    "extensionAttribute12"
    "extensionAttribute14"
    "extensionAttribute2"
    "extensionAttribute3"
    "extensionAttribute4"
    "extensionAttribute5"
    "extensionAttribute6"
    "extensionAttribute8"
    "extensionAttribute9"
    "Fax"
    "GivenName"
    "HomeDirectory"
    "HomedirRequired"
    "HomeDrive"
    "HomePage"
    "HomePhone"
    "Initials"
    "instanceType"
    "isDeleted"
    "l"
    "LastBadPasswordAttempt"
    "LastKnownParent"
    "LastLogonDate"
    "legacyExchangeDN"
    "LockedOut"
    "lockoutTime"
    "logonCount"
    "LogonWorkstations"
    "mail"
    "mailNickname"
    "Manager"
    #"MemberOf"
    @{l='membership';e={($_.Memberof)[0..20]}} #to prevent this value to become too large to fit into Excel cell limit
    "MNSLogonAccount"
    "MobilePhone"
    "Modified"
    "modifyTimeStamp"
    "Name"
    "ObjectCategory"
    "ObjectClass"
    "Office"
    "OfficePhone"
    "Organization"
    "OtherName"
    "PasswordExpired"
    "PasswordLastSet"
    "PasswordNeverExpires"
    "PasswordNotRequired"
    "physicalDeliveryOfficeName"
    "POBox"
    "PostalCode"
    "preferredLanguage"
    "ProfilePath"
    "ProtectedFromAccidentalDeletion"
    #"proxyAddresses"
    @{l='allEmailAddr';e={$_.proxyAddresses}}
    "SamAccountName"
    "sAMAccountType"
    "ScriptPath"
    "sDRightsEffective"
    #"ServicePrincipalNames"
    @{l='SPN';e={$_.ServicePrincipalNames}}
    "SmartcardLogonRequired"
    "sn"
    "st"
    "State"
    "StreetAddress"
    "Surname"
    "targetAddress"
    "Title"
    "TrustedForDelegation"
    "TrustedToAuthForDelegation"
    "UseDESKeyOnly"
    "userAccountControl"
    "UserPrincipalName"
    "whenChanged"
    "whenCreated"
)

Apr 3, 2012

WMI Association Class

There is a special type of WMI class called "association class". This type of class binds two normal, related classes together. A typical example is association class for NIC-related classes. For each NIC in a system, there are two WMI classes for it: Win32_NetworkAdapterWin32_NetworkAdapterConfiguration. The former mainly includes NIC hardware info, such as speed, MAC, media connection status, etc; the later mainly includes configuration info on a NIC, such as IP, DHCP, DNS, etc. More than often, you need to obtain info from both classes, and that's where association class comes to help.

Still using NIC as our example, windows defines an association class called Win32_NetworkAdapterSetting, through which you can access info from both above-mentioned classes. An association class include two members, one called element, the other called setting. Not surprisingly, element links to a Win32_NetworkAdapter object (because it is the element) and setting links to a Win32_NetworkAdapterConfiguration object (because it is the setting stuff). Below is how you use it:

$ac = Get-WmiObject -Class win32_NetworkAdapterSetting   #gets all NIC info
$connectedAdapters = $ac | where {([wmi]$_.element).netConnectionStatus -eq 2}
$connectedAdapters | foreach {([wmi]$_.setting)|select caption, dhcpEnabled,IPaddress,dnsServerSearchOrder }

Mar 8, 2012

[Powershell] Try-Catch fails to catch an exception?

I was running a script that does WMI query and found that my try-catch-final statement seemed not working. The exception was still shown on console instead of handled by my catch block.

It turns out that exceptions are categorized into two groups, terminating exceptions and non-terminating exceptions. By default, try-catch intercepts only terminating exceptions. No surprisingly, get-WMIobject exceptions are non-terminating exceptions.

There are two ways to make it work. One is to make all exception terminating by below assignment:

$ErrorActionPreference = "Stop"; #Make all errors terminating


Remember to reset the preference at the end of your script as this is global.


$ErrorActionPreference = "Continue"


Or right after get-WMIobject statement, check the value of $?


if ($?){ 
        #processing block
}
else {
       throw $error[0].exception
}

Retrieving Terminal Server Configuration Settings Using Powershell

It was quite easy for Windows 2003 TS servers with Win32_TerminalServiceSetting WMI class, there are tons of documents on the Net. It took me some time, however, to find out that MS change the class considerably for Windows 2008.

It's now under a different name space root\cimv2\TerminalServices. It also requires you to specify an authentication flavour before you can gain access.

In short, you get info with below commands (w2k3 and w2k8 respectively):

gwmi Win32_TerminalServiceSetting -computername -namespace root/cimv2/TerminalServices -authentication 6

or

gwmi Win32_TerminalServiceSetting -computername [-namespace root/cimv2]

Apr 20, 2011

Using System Namespace In Powershell

There are many cool pre-defined constants, functions, methods, and etc. in System object. One would normally learn individual ones through sample scripts, but really should browse the MSDN page to explore what System namespace has to offer. Go to a class/structure/enumeration that you are interested, then pay special attention to those static members.

A few examples:

[System.DateTime]::Today  versus [System.DateTime]::Now
[System.String]::Empty
[System.Console]:: almost everything are static, not surprisingly
[System.Math]::PI

There are also a bunch of other namespaces, please see .Net Framework Libraries