Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell how to get a reference to a function or cmdlet?

Tags:

powershell

I would like to get a reference to a function or cmdlet.

For instance, I would like to reference the Get-ChildItem cmdlet. I don't want to call it, I want a reference to the function, that I could then pass to another function.

Is there a syntax to do this?

I am aware that I can Invoke-Expression with a string 'Get-ChildItem'. Is this the only way to handle this situation?

like image 379
Josh Petitt Avatar asked Sep 12 '25 20:09

Josh Petitt


2 Answers

$gci = Get-Command Get-ChildItem

This will do it.. but since you haven't said how you want to use it I'm not sure if this is what you want.

Edit: after seeing your comment, it seems you want to store it in a variable. You could do that with script functions, but I don't think you could do that with a cmdlet's contents like that, unless you wrap it in a scriptblock first.

like image 177
briantist Avatar answered Sep 14 '25 19:09

briantist


Invoke-Expression is the tool made to handle just this use case. Note that if you need to define some variables within a string when it is executed, you should escape the variable with a grave mark ` or you can instead define the here-string with a single quote instead.

$commands = @"
`$computername = `$env:computername
get-wmiobject win32_computersystem -computername `$computername
"@

Invoke-Expression $commands
>Domain              : FOXDEPLOY
Manufacturer        : Dell Inc.
Model               : Latitude E6540
Name                : DELLBOOK
PrimaryOwnerName    : Windows User
TotalPhysicalMemory : 17080483840
like image 24
FoxDeploy Avatar answered Sep 14 '25 19:09

FoxDeploy