'Get the last command executed on a PowerShell script

I'm updating the logging function I use for all my scripts and making it compatible with the SCCM logging viewer.

Under the fields that the SCCM viewer takes is the component field, and I'll like to fill it with the main command that it's run and I'm logging. For example, if I'm logging "Data copied" and I did that with Copy-Item, I'd like that the logs says Copy-Item for that line of the log.

So far I've tested the following methods, using $$ and the history cmdlets (Get-History, Add-, etc.), but they only work with the PowerShell console, not with script execution.

The final result I'd like to get is:

Enter image description here



Solution 1:[1]

I think this is what you're talking about?

$Folder = "some path"

$Cmdline = 'Remove-Item $Folder -Force -Recurse'
Invoke-Expression $Cmdline
Write-Host $Cmdline.replace("`$Folder",$Folder)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robbie P