Ben
Ben

Reputation: 53

Use a function loaded in a string

Okay this is a weird one but so image my code is,

$string = "Function Get-Something {Write-host 'You got something'}"

now i want to load that function from the string into my PS memory so i can call it... so Invoke-Expression "$string" will do this but i need to use the invoke line within another function. functception..

function Validate-something {

$string = "Function Get-Something {Write-host 'You got something'}"
invoke-expression $string
}
Validate-Something
Get-something

Any ideas on how to make this work?

note: I cant write the string to a file first.

Upvotes: 1

Views: 58

Answers (2)

Ben
Ben

Reputation: 53

okay, worked it out...

So I needed to set the scope of the fuctions I'm calling e.g.

function Validate-something {
$string = "Function script:Get-Something {Write-host 'You got something'}"
invoke-expression $string
}
Validate-Something
Get-something

Hope this helps anyone in the future...

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Dot-source the defining function to have the inner function accessible in the calling scope subsequently:

. Validate-Something
Get-Something

Upvotes: 1

Related Questions