Is there a way to hook into an internal PowerShell function event?

Viewed 299

Is there a way to hook into an internal PowerShell function event? Specifically looking to add code to the Copy-Item function when the call is started, finishes or errors out. I know I can just override the function but I was trying to avoid rewriting that code.

How would you even get what events are available for Copy-Item?

2 Answers

Have a look at proxy functions:

$MetaData = New-Object System.Management.Automation.CommandMetaData (Get-Command  Copy-Item)
[System.Management.Automation.ProxyCommand]::Create($MetaData) 

It does require writing some code, of course, but it's certainly easier than recompiling a core DLL.

It's written in C#, but you can get to it.

Run

Get-Command -Name Copy-Item | Select-Object -ExpandProperty DLL

to find the DLL it's part of.

The use dotpeek https://www.jetbrains.com/decompiler/ and open the DLL there.

Finally navigate to "Microsoft.PowerShell.Commands", expand it then double click CopyItemCommand and you'll get the source code.

EDIT: I realize that's not quite an answer to your question. But afaik the only way to reuse the code is to use that source code to compile a new DLL and load that as a module in PowerShell overwriting the original cmdlet.

Related