I am not very experienced with PowerShell. I am working on something that when I put it in a write-host, it seems to work OK. When I then put it into my main script, it fails. Note, if I manually expand out the searchbase, instead of using the variable, the script works OK. I’m setting up a ‘template’ script that others at my company could use for multiple domains, without needing to change the script at all. The searchbase variable however does not seem to be expanding, so the command fails. I’ve tried {}, (), and “”. Help!
That should work fine. Additionally, there’s no need for -SearchBase “$searchb”, just use -SearchBase $searchb.
The problem you’re doubtless running into is that you expect $strDomain to contain a domain name as a string. It does not. It contains a domain object, with many properties. You probably meant to…
$strDomain = Get-ADDomain -Current LocalComputer | Select-Object -Expand Name
I’ll also selfishly recommend Learn Windows PowerShell in a Month of Lunches as a good way to not get clobbered by that stuff, and Learn PowerShell Toolmaking in a Month of Lunches as a way to not go down the wrong path in writing these tools for other people to use ;).
That way you can confirm that your variables contain what you expected them to. 99.2% of bugs are from a variable containing something other than what you thought it did. The first step is always to confirm from inside the script, not using Write-Host (which is an entirely different creature).
Thanks, Don! I haven’t had a chance to dig back into this today, but you’ve given me a great amount to look over.
The concept of the script, is to be able to have any tech run this at a client, regardless of the domain, and without editing the script. The script will check the default Computers OU, and IF there are ANY objects in there “like Windows…” then it will write a text file containing the names of those objects. If there are not, it will then exit.
In the long run, I’ll be tying in an RMM tool to monitor for that text file… =)
That’s been a huge help so far - thank you! I was able to track down that it’s “DistinguishedName” that I need to expand. Here is what I have now, and below that is the error I’m getting.
The if statement does work - when I manually type out the searchbase, rather than using the variable, which is why I was thinking it has to be something related to that which I’m doing wrong.