1

When working in a POSIX shell, I can use the builtin type to see how an executable, shell function, builtin, or alias is defined.

For instance, I have a shell function box, which will draw an ASCII box around a given piece of text:

$ box "I am the operator of my pocket calculator"
#############################################
# I am the operator of my pocket calculator #
#############################################

and I can see how the function is defined like this:

$ type box
box is a function
box ()
{
    t="$1xxxx";
    c=${2:-#};
    echo ${t//?/$c};
    echo "$c $1 $c";
    echo ${t//?/$c}
}

Is there a PowerShell equivalent? I'm particularly interested in seeing PowerShell functions that I have defined in $profile, and seeing how they are defined -- I've been using

type $profile

to show all of them, but I want something a little more targeted. (Note that the PowerShell/Cmd command type is equivalent to the Unix cat and is not in any way related to the Unix type builtin that I'm asking about.)

2 Answers2

2

Not every command is a function.

In order to find out if your command is indeed a function, type:

get-command "name of command"

For example:

PS> get-command box_

CommandType Name Version Source


Function Box

Now that we have determined that it is indeed a function, you can see the content of the function like this:

(get-command box).ScriptBlock

See also: https://www.pdq.com/blog/viewing-powershell-function-contents/

Personally, I added the following to my Powershell Profile:

cls
write-host -ForegroundColor Cyan "Powershell started with custom functions."
write-host -ForegroundColor Cyan "They are: EditCustomFunctions, name1, name2, etc..."

function EditCustomFunctions { if (!(Test-Path (Split-Path $profile))) { mkdir (Split-Path $profile) } ; if (!(Test-Path $profile)) { New-Item $profile -ItemType file } ; powershell_ise $profile

}

So from within Powershell I can just type EditCustomFuctions to open PowerShell ISE with my profile to edit the functions, and my custom welcome message lists all my custom functions.

LPChip
  • 66,193
1

I've accepted LPChip's answer because he gave me exactly the information that I needed; I'm adding a PowerShell function here that I'm actually going to use -- it's just a thin wrapper around Get-Command that does the CommandType check before printing the ScriptBlock.

function showfunc {
    param($function_name)
$command=Get-Command "$function_name"
if ($command.CommandType  -match "Function") { $command.ScriptBlock }

}