'Why can't the variable be passed?

I have the following problem. I get no output with the following command and no error message either. However, if I take the line by itself and replace $n with the username or just part of it, it works.

$n = Read-Host -Prompt "Benutzer eingeben"
    
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and Name -like "*$n*"} -Properties Name, DisplayName, msDS-UserPasswordExpiryTimeComputed | Select-Object -Property Name, Displayname,@{Name="Expiration Date";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

I would be grateful for a tip



Solution 1:[1]

If curly braces are used to enclose the filter, the variable(in this case it's $n) should not be quoted.

Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and Name -like $n} -Properties Name, DisplayName, msDS-UserPasswordExpiryTimeComputed | Select-Object -Property Name, Displayname,@{Name="Expiration Date";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

Here is the relevant part from the documentation.

if the filter expression is double-quoted, the variable should be enclosed using single quotation marks: Get-ADUser -Filter "Name -like '$UserName'". On the contrary, if curly braces are used to enclose the filter, the variable should not be quoted at all: Get-ADUser -Filter {Name -like $UserName}.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdul Niyas P M