I'm trying to figure out a way to handle image metadata extraction in PowerShell for several manufacturing sites. Each site has a different way of organizing images, and I want to standardize how I process their paths and metadata to dump it into a database. I've got the data extraction part down, but I'm struggling with efficiently parsing these paths using different methods for each site's setup. Is there a way in PowerShell to define a function as a property (like a callback) that can be executed dynamically? I'm looking for something that doesn't involve a bunch of if/else statements, ideally something that leverages OOP principles or similar functionality.
3 Answers
Instead of functions, you can treat `$site.PathParser` as a scriptblock. Then, call it with any parameters you need. If you're into OOP, you could define base and derived classes implementing the same method, keeping your code tidy! Here's a quick snippet for clarity:
```
$sites = @(
@{
Prop1 = 'val1'
Prop2 = 'val2'
PathParser = {
param(
$param1,
$param2
)
Do-Stuff $param1 $param2
}
}
)
$sites | ForEach-Object {
& $_.PathParser -param1 'someVal' -param2 'anotherVal'
}
```
You can achieve a similar outcome using `Invoke-Expression`. Just build your string with the PathParser function and execute it. Here's how:
```
$sites | % {
$site = $_
# More processing...
$data = "$($site.PathParser) $($_.DirectoryPath)" | Invoke-Expression
}
```
This method can give you more flexibility! Check the official documentation for more info.
You might want to use a switch statement on the path to capture metadata as variables for a PSCustomObject. That way you can easily manage the extracts! I would code up an example if I wasn't on my phone, but it works well with the syntax.

Totally get that! I also prefer cleaner OOP styles instead of just if/else. There are definitely smoother ways to achieve what you're looking for.