The way our business is set up, our custom cmdlets are spread out across the network in several different larger files. We refer to these files in the usual "Microsoft.PowerShell_profile.ps1"
Is there something I can run within Powershell to find where a cmdlet is running from instead of manually going through all the files referenced in "Microsoft.PowerShell_profile.ps1" to find it?
E.g. if I have written a cmdlet called Get-UserExpiry and it is saved in C:\User\Name\Documents\CustomCmds.ps1, and I include that file path in Microsoft.PowerShell_profile.ps1, is there a command I can use to find that file path if all I know is the cmdlet name?
CodePudding user response:
Get-Command
should mostly do the job with anything that come your way.
You can access the Module
or Module.Path
to get more insight on the current cmdlet.
That being said, profile functions won't show a module nor a file source using that command. It is possible though to get that information from the $function
PSDrive by using ${Function:Get-Stuff}
(where Get-Stuff
need to be replaced by the name of your function).
Here's a combination of these 2 ways of seeing the command location bundled together in 1 function.
Function definition
Function Get-CommandLocation($Command) {
$Source = (Get-Command -Name $Command)
if ($null -ne $Source -and !([String]::IsNullOrEmpty( $Source.Source))) { return $source.Module.Path }
$source = [scriptblock]::Create(('${Function:{0}}'.replace('{0}',$Command))).Invoke()
if ($null -ne $Source.Module) { return $Source.Module.Path }
return $source.File
}
Examples
Get-CommandLocation Get-Item # Native cmdlet
# Value obtained from (Get-Command Get-Item).Module.Path
# Return C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1
Get-CommandLocation Edit-Profile # Profile function
# Value obtained from ${Function:Edit-Profile}.File
# Return C:\Users\SagePourpre\Documents\WindowsPowerShell\Microsoft.VSCode_profile.ps1
Get-CommandLocation New-ExternalHelp # PlatyPS module downloaded from the gallery
# Value obtained from (Get-Command New-ExternalHelp).Module.Path
# Return C:\Program Files\WindowsPowerShell\Modules\platyPS\0.14.2\platyPS.psm1