Link to home
Start Free TrialLog in
Avatar of ptea
ptea

asked on

Powershell losing variables

Hi there,

sometimes variables are losing their values and I dont know why - e.g.:

$Comp = gwmi -query ("Select SystemType,DnsHostName,Domain,DomainRole from Win32_ComputerSystem")

If ($comp.DomainRole -match "3")
{
$SetUsername=$comp.domain+'\'+$UserName
$domain = New-Object DirectoryServices.DirectoryEntry
$search = [System.DirectoryServices.DirectorySearcher]$domain
$search.Filter = "(&(objectClass=Computer)(cn=$comp.dnshostname))"
$Computer = $search.FindOne().GetDirectoryEntry()
}

The variable $comp.dnshostname is not working at this position:

$search.Filter = "(&(objectClass=Computer)(cn=$comp.dnshostname))"


But if I put the variable into a new one it works - e.g.

$Comp = gwmi -query ("Select SystemType,DnsHostName,Domain,DomainRole from Win32_ComputerSystem")

If ($comp.DomainRole -match "3")
{
$SetUsername=$comp.domain+'\'+$UserName
$GetComp=$comp.dnshostname
$domain = New-Object DirectoryServices.DirectoryEntry
$search = [System.DirectoryServices.DirectorySearcher]$domain
$search.Filter = "(&(objectClass=Computer)(cn=$getcomp))"
$Computer = $search.FindOne().GetDirectoryEntry()
}

I put the variable $comp.dnshostname into a new one $GetComp:

$GetComp=$comp.dnshostname

Now it works at the above mentioned position:

$search.Filter = "(&(objectClass=Computer)(cn=$GetComp))"

Why can't I work with $comp.dnshostname directly?

Cheerio


ASKER CERTIFIED SOLUTION
Avatar of KenMcF
KenMcF
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ptea
ptea

ASKER

works - thx