Skip to content

Instantly share code, notes, and snippets.

@sayedihashimi
Created February 3, 2014 05:57
Show Gist options
  • Save sayedihashimi/8779449 to your computer and use it in GitHub Desktop.
Save sayedihashimi/8779449 to your computer and use it in GitHub Desktop.
PowerShell: Add a function with a parameter to an object
$result | Add-Member -MemberType ScriptMethod ExpandString -Value {
[cmdletbinding()]
param(
[Parameter(
Mandatory=$true)]
[string]
$unexpandedValue
)
process{
if($this.ProjectInstance){
return $this.ProjectInstance.ExpandString($unexpandedValue)
}
else{
'project is null'
}
}
}
@aaroncalderon
Copy link

aaroncalderon commented Sep 6, 2018

So,

I am guessing this could be used like this:

[PSCustomObject]$result = @{ 
    a = 'a' 
    ProjectInstance = $ExecutionContext.InvokeCommand
} 

$result | Add-Member -MemberType ScriptMethod ExpandString -Value {
     [cmdletbinding()]
     param(
         [Parameter(
             Mandatory=$true)]
         [string]
         $unexpandedValue
     )
     process{
         if($this.ProjectInstance){
             return $this.ProjectInstance.ExpandString($unexpandedValue)
         }
         else{
             'project is null'
         }
     }
 }
 $result.ExpandString('aaa')

But, I get an error, so my guess is wrong.

An example would be helpful.

Thanks

Update

I updated the declaration of $result. However, I do not see how this would be practical.

The piece of adding the method works, which I think is the point of the example.

@fsackur
Copy link

fsackur commented Feb 16, 2019

@aaroncalderon, you have added the scriptmethod to $result but you're trying to invoke it on ProjectInstance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment