Home > database >  Get-ADCompter command returns back null response
Get-ADCompter command returns back null response

Time:03-04

I'm trying to combine a string and an int together to get the output JWang1 but everytime I run this command it keeps returning back null, any help is appreciated, thank you

$pcname = "Jwang"
$number = 1
Get-ADcomputer -filter "name -like '$pcname   $number'" | select -ExpandProperty name

The goal is to get the command to search "JWANG1", but the result keeps coming back null

Alternatively if I do this, I get a search result posted back to me

$pcname = "Jwang1"
Get-ADcomputer -filter "name -like '$pcname'" | select -ExpandProperty name

The difference here is that I am not trying to combine the string and int, but how do I get it to combine and work?

CodePudding user response:

In this case you would need to use the Subexpression operator $(..) to resolve the concatenation operation:

$pcname = "Jwang"
$number = 1

"name -like '$pcname   $number'"
# Interpolates both variables without resolving the concatenation
# Results in: name -like 'Jwang   1'

"name -like '$($pcname   $number)'"
# Resolves the expression inside `$(..)` before interpolating it
# Results in: name -like 'Jwang1'

As aside, the right operator for your query to Active Directory should be -eq instead of -like since you're not using any wildcard for your query.

CodePudding user response:

The issue is how string expansion works, and how you're using it. Right now you have:

"name -like '$pcname   $number'"

Once you sub in the values for those variables it reads like this:

"name -like 'JWANG   1'"

There's several ways you could go about correcting this. The first is to simply remove the from the string so it reads like this:

"name -like '$pcname$number'"

The second way is to put in a subexpression like this:

"name -like '$($pcname   $number)'"

Or you could combine them before you reference it like:

$pcname = "Jwang"
$number = 1
$combinedname = $pcname   $number
Get-ADcomputer -filter "name -like '$combinedname'" | select -ExpandProperty name
  • Related