0

I'm trying to get the Username from Get-AppxPackage. Unfortunately that property is nested quite deep. In my head it would be something like this (but it doesn't work):

Get-AppxPackage -Allusers | select $_.PackageUserInformation.UserSecurityID.Username | where-object {$_.PackageUserInformation.UserSecurityID.UserName -notlike "defaultuser*"}

In UserName, there could be either 1 or 2 items depending on the package. If there are 2 items, I want to put the one that is not like 'defaultuser*' into a variable as a string.

Running Get-AppxPackage -Allusers | where-object {$_.PackageUserInformation.UserSecurityID.UserName -like "defaultuser*"} 

Should return some example packages with multiple UserName items that are built into Windows 10.

bad_coder
  • 11,289
  • 20
  • 44
  • 72

2 Answers2

0

Filter your object first, then select and output the result - you can select "nested" properties using a calculated property structure:

$PackagesAndUsers = Get-AppxPackage -Allusers | Where-Object { $_.PackageUserInformation.UserSecurityID.UserName -notlike "defaultuser*"} | Select Name, @{N='UserName';E={$_.PackageUserInformation.UserSecurityID.UserName}}

Now you have all the packages and users in a single object which excludes defaultuser* From $PackagesAndUsers - you can pick anything you like out of this to populate your string.

Bear in mind there could still be more than one user in the Username field if there's more than one user on your computer

Scepticalist
  • 3,737
  • 1
  • 13
  • 30
0
  • The following extracts the usernames that don't start with defaultuser from among the users that have installed all AppX packages on the local machine.

  • Given that there are likely to be many duplicates, consider piping to Sort-Object -Unique to get the unique set of resulting usernames.

Get-AppxPackage -AllUsers |
  ForEach-Object {
    @($_.PackageUserInformation.UserSecurityID.Username) -notlike 'defaultuser*'
  }

Note the use of @(…), the array-subexpression operator, which ensures that the LHS is an array.

With a collection (such as an array) as the LHS, PowerShell comparison operators such as -notlike act as filters and return an array of matching items rather than a Boolean - see about_Comparison_Operators.

Therefore, the above simply filters out usernames that start with defaultuser from the (potential) array of usernames reported by $_.PackageUserInformation.UserSecurityID.Username


As for what you tried:

... | select $_.PackageUserInformation.UserSecurityID.Username

  • $_ is only ever meaningfully defined inside script blocks ({ ... }) - see this answer.

  • Even without it, you cannot provide property paths to Select-Object (whose built-in alias is select) - see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775