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?
$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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With