As Mathias R. Jessen points out, it is generally preferable to use a parameterized SQL query than to use string interpolation to bake values into a query string, not least for better security, but also to avoid round-trip conversion to and from strings for non-string values.
If you do want to stick with your string-interpolation approach, here's a solution based on the .psobject
intrinsic member, which is a rich source of reflection about any object and allows enumerating its properties via the .Properties
collection:
# Sample input object.
$line = [pscustomobject] @{
'common.uuid' = '1-2-3';
'user.user_id' = 'jdoe';
}
# Use string interpolation to embed all of the object's property values.
$q = @"
Values (
$($line.psobject.Properties.Value.ForEach({ "'" + $_ + "'" }) -join ",`n ")
)
"@
This solution makes two assumptions:
You're interested in the values of all properties of the input object.
You do not need nested property access (in the code in your question, a property access such as .'user.user_id'
is a single property access targeting a property named verbatim user.user_id
, even though the name itself suggests a property path (nested access)).
If these assumptions don't hold, see Daniel's helpful answer.
Note that, as in your question, all values are represented as strings ('...'
) in the resulting query fragment.
If you choose a parameterized-query approach instead, you can similarly use $line.psobject.Properties.Value
to obtain an array of all property values. (Note that even though .Value
is applied to a collection of elements, PowerShell conveniently collects its elements' .Value
values, which is a feature known as member-access enumeration).
The above stores the following in variable $q
:
Values (
'1-2-3',
'jdoe'
)
See this answer for an overview of PowerShell's string interpolation via expandable strings ("..."
).