I have a couple of problems I’m encountering when using Select-Object with an AWS cmdlet (Get-IAMRole) and hope someone could explain where I’m going wrong?
When selecting object properties that are piped through from “Get-IAMRole” I’ve found one of them is a “NoteProperty”. I’ve been able to access this using the “ExpandProperty” parameter. The output provides me with a date and time. However, I would prefer to only have the date but I’ve been unable to separate them. Any suggestions on how I can can achieve this? I have tried but failed so far.
My full script simply gets the objects (IAM Roles), pipes them through to select-object where I select the information I want, then outputs this information to a .csv file. I’ve found that if one of the object properties is empty/null it doesn’t appear in the output to the .csv. I believe I’ve narrowed this down to the select-object cmdlet, rather than the export to .csv, as removing the property (-ExpandProperty “RoleLastUsed”) from select-object gives me the expected results. Any advice on how I can prevent Select-Object from dropping the object if one of the selected properties is empty/null?
Below is part of the script. I’ve already created a .txt file with the role names
$RoleNames = Get-Content D:\temp\RoleNames_$account.txt
foreach ($name in $RoleNames){
# ExpandProperty is required to access the last used date.
Get-IAMRole -Credential $creds -rolename $name |`
Select-Object -Property RoleName, CreateDate, Arn, RoleId, Path, Description -ExpandProperty "RoleLastUsed" |`
export-csv D:\temp\RoleDetails_$account.csv -NoTypeInformation -Append
}
If you need to use -ExpandProperty it indicates that the property is either an array or has sub properties.
Since I don’t have any experience with AWS and no access to it neither I cannot tell what RoleLastUsed could be. With your describtion I’d suspect it could have sub properties.
Using @{Name = 'LastUseDate'; Expression = {$_.RoleLastUsed.LastUsedDate.Date}} solved the issue of RoleNames with null LastUsedDate properties not being passed through to the .csv. However, it didn’t remove the time from the LastUsedDate output. Instead, the output was displayed like this - 9/27/2022 0:00 - where the times are all 0:00. While this isn’t perfect, the fact that I’m not losing any of the RoleName objects without a LastUsedDate property is good for me.
Using @{Name = 'LastUseDate'; Expression = {$_.RoleLastUsed.ToString('dd-MM-yyyy')} was the same as above except it didn’t provide any properties for LastUsedDate. While all the RoleNames existed the LastUseDate column was empty.
Do you happen to know why changing from using the ExpandProperty parameter to the array stopped me from losing RoleName objects with no LastUsedDate property?
Also, thanks for you help! I’ll mark your previous response as the solution as it has fixed the main issue I was encountering.