PowerShell not storing a variable

Hi, All.

I have this little line of PowerShell code (running it in VS Code) that goes out to get the services on a remote machine. Once it get’s that dump of services from the remote machine I’m trying to store that in a var so filtering can be done with the data that’s stored rather than make several calls to the same server for the same information. And everything works as it should except for the IF (below).

The problem is that the var isn’t storing the dump from the remote box like I would think it would. Every time I run the script, it invokes the command to get the data. Here’s what I have:

IF(-not($GetServices)){
$GetServices = Invoke-Command -ComputerName $Server -ScriptBlock {Get-WmiObject -Class Win32_Service}}

Essentially, if the $GetServices var is empty, go get the information. If it’s not empty, skip past it and do the rest of the script.

I’m not nulling the var at any point in the script, and I do the filtering to find the services that are set to automatic start later in the script and it works. But $GetServices isn’t retaining that data even in the same session.

Would anyone have an bit of knowledge they can drop on me that would explain why this is happening?

Thank you.

Hi,

Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working). If you can’t see the </> in your toolbar, you will find it under the gear icon.

How to format code on PowerShell.org

The code as you’ve posted it will work as intended, and you can check that like this:

if (-not($GetServices)) {
    "Getting Services"
    $GetServices = Invoke-Command -ComputerName 'localhost' -ScriptBlock { Get-WMIObject -Class Win32_Service}
}
else {
    "Already Got Services"
}

If you run that repeatedly, after the first run you’ll see "Already Got Services" every time.

You really need to share more detail about the rest of your script but I suspect it’s a scope problem.

Regardless of the very helpful and correct answer from Matt …

You don’t have to use Invoke-Command to get the desired information from one or more remote comptuers.

And you should not use Get-WmiObject anymore.

Instead you should use it’s successor

So your code could be something like this:

if (-not($GetServices)) {
    $GetServices = Get-CimInstance -ComputerName 'localhost' -ClassName Win32_Service
}else {
    "Already Got Services"
}

Thanks, All.

I thought I was formatting the code correctly. I was told that in a previous post and thought I corrected it. Obviously I misunderstood how that’s done. Thank you for the additional correction.

I will give these both a try. If CIM-Instance is the new thing, then I’ll use that instead.

Thanks again.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.