问题
I have a string that looks something like this:
$string = "property1.property2.property3"
And I have an object, we'll call $object
. If I try to do $object.$string
it doesn't interpret it that I want property3
of property2
of property1
of $object
, it thinks I want $object."property1.property2.property3"
.
Obviously, using split('.')
is where I need to be looking, but I don't know how to do it if I have an unknown amount of properties. I can't statically do:
$split = $string.split('.')
$object.$split[0].$split[1].$split[2]
That doesn't work because I don't know how many properties are going to be in the string. So how do I stitch it together off of n
amounts of properties in the string?
回答1:
A simple cheater way to do this would be to use Invoke-Expression
. It will build the string and execute it in the same way as if you typed it yourself.
$string = "property1.property2.property3"
Invoke-Expression "`$object.$string"
You need to escape the first $
since we don't want that expanded at the same time as $string
. Typical warning: Beware of malicious code execution when using Invoke-Expression
since it can do anything you want it to.
In order to avoid this you would have to build a recursive function that would take the current position in the object and pass it the next breadcrumb.
Function Get-NestedObject{
param(
# The object we are going to return a propery from
$object,
# The property we are going to return
$property,
# The root object we are starting from.
$rootObject
)
# If the object passed is null then it means we are on the first pass so
# return the $property of the $rootObject.
if($object){
return $object.$property
} else {
return $rootObject.$property
}
}
# The property breadcrumbs
$string = '"Directory Mappings"."SSRS Reports"'
# sp
$delimetedString = $String.Split(".")
$nestedObject = $null
Foreach($breadCrumb in $delimetedString){
$nestedObject = Get-NestedObject $nestedObject $breadcrumb $settings
}
$nestedObject
There are some obvious places where that function could be hardened and documented better but that should give you an idea of what you could do.
回答2:
What's the use case here? You can split the string as you've described. This will create an array, and you can count the number of elements in the array so that n
is known.
$string = "property1.property2.property3"
$split = $string.split('.')
foreach($i in 0..($split.Count -1)){
Write-Host "Element $i is equal to $($split[$i])"
$myString += $split[$i]
}
来源:https://stackoverflow.com/questions/45174708/powershell-turn-period-delimited-string-into-object-properties