Why does the WMI PSComputerName change based on this usage inserting into mysql database?

I am writing a script to perform WMI queries, get the disk information from the server and put the info in a mysql database. When I perform the following code, I get "\servernameootcimv2:Win32_LogicalDisk.DeviceID="C:".PSComputerName" put in the DB for computername.

foreach ($Server in $Servers) {
    $DiskInfo = get-wimobject -class Win32_LogicalDisk -ComputerName $Server

    foreach ($disk in $DiskInfo) {
        $command.CommandText = "INSERT INTO drives (computername) VALUES ('$disk.PSComputerName')"
        $command.ExecuteNonQuery()
    }

}

When I modify the code to the following by assigning $disk.PSComputerName to a variable and using that, I get the right output in the DB of just the server name.

foreach ($Server in $Servers) {
    $DiskInfo = get-wmiobject -class Win32_LogicalDisk -ComputerName $Server

    foreach ($disk in $DiskInfo) {
        $name = $disk.PSComputerName 
        $command.CommandText = "INSERT INTO drives (computername) VALUES ('$name')"
        $command.ExecuteNonQuery()
    }

}

I realize I have a workaround in place, but I'm trying to understand the difference in this behavior.

Answers


Powershell expands only variables in double quoted strings. In your query string

"INSERT INTO drives (computername) VALUES ('$disk.PSComputerName')"

only $disk is expanded (to the return value of its ToString() method), not the property $disk.PSComputerName. You need to put it in a subexpression to make powershell evaluate the property value:

"INSERT INTO drives (computername) VALUES ('$($disk.PSComputerName)')"

See here for a more thorough explanation.


Within an expandable string, you need to use substring syntax - $() - to reference a property of an object.

$command.CommandText = "INSERT INTO drives (computername) VALUES ('$($disk.PSComputerName)')"

otherwise the property reference .PSComputerName is interpreted as literal text to be appended onto the value of $disk.


Need Your Help

Setting all values in a boolean array to true

java arrays variables boolean

Is there a method in Java for setting all values in a boolean array to true?

InfoWindow - Google map API

javascript google-maps

I try to add infowindows for all my markers. But I add only one InfoWindow for last marker.