0

I have an object that contains a field named PKBlock which accepts a script value

$o.PKBlock = { return $_.UserId }

or

$o.PKBlock = { return $_.GroupId + $_.ResourceId }

I would like to pass an object (shown here in json)

{
    "UserId":"aodpkjpw92kjd",
    "GroupId":"90djd0223djd",
    "ResourceId":"012ekkkk023"
}

How do I execute the script block and get the return value?

I have tried the following (where $record is the object as an object):

Invoke-Command -ScriptBlock $o.PKBlock -InputObject $record
Invoke-Command -ScriptBlock $o.PKBlock -ArgumentList $record
$record | Invoke-Command -ScriptBlock $o.PKBLock
  • Here ya go: https://stackoverflow.com/questions/16575419/powershell-retrieve-json-object-by-field-value . This should answer your question – Abraham Zinala Mar 24 '21 at 14:59
  • @AbrahamZinala much appreciated, but the link is telling how to get values and does not contain any information regarding script blocks that I am seeing. I do not believe this applies to my question. I am wanting to use a script block to generate a primary key from an object programatically. – Richard Hankins Mar 24 '21 at 15:04

1 Answers1

2

First, the unnamed automatic variable in a scriptblock is $args. First argument is $args[0], second is $args[1], etc. All arguments are contained in just $args

You can invoke the scriptblock a few different ways.

&  # call operator, new child scope

.  # call operator, calling scope. Also used for "dot sourcing"

Invoke-Command

Next issue is if you want to access the json properties by name you'll need to make that an object. Probably the easiest is ConvertFrom-Json. Once you have those two corrected, any of these should work.

$o.PKBlock = { return $args[0].userid } 

$json = @'
{
    "UserId":"aodpkjpw92kjd",
    "GroupId":"90djd0223djd",
    "ResourceId":"012ekkkk023"
}
'@ | ConvertFrom-Json

Now call it

& $o.PKBlock $json

or

. $o.PKBlock $json

or

Invoke-Command -ScriptBlock $o.PKBlock -ArgumentList $json

You could also provide named parameters for your scriptblock

$o.PKBlock = {
    Param($object) return $object.userid
} 

Call it the same way.

EDIT

$_ or $PSItem is automatic variable for any number of cmdlets. If you really want to use that vs args/named parameters, you can pass into Foreach-Object

$json | ForEach-Object {. $o.PKBlock $_}

or

$json | ForEach-Object {. $o.PKBlock $psitem}
Doug Maurer
  • 8,090
  • 3
  • 12
  • 13