Is there any way to have powershell automatically run a command anytime a command is run

Viewed 38

I'm wanting to be able to have PowerShell automatically run a specified command anytime anything is run in PowerShell(hitting enter, any command at all). I've searched all over google with no luck finding anything except the way to have a command run on startup of powershell

1 Answers

If you need it a bit hidden you could do it with a ScheduledTask and Auditing Events.

Enable Auditing to get all changes logged as events https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/wmf/whats-new/script-logging?view=powershell-7.2&viewFallbackFrom=powershell-6

Create a Scheduled Task that starts with a trigger from Events by ID. Take the IDs from the Microsoft article above. Add the command you would like to run as action. This means command is "PowerShell" and parameters are like -NonInteractive -Windowstyle minimized -c "command was executed | out-file c:\temp\activity.log"

Set it to be run as the user "system" if you want it at full permission without user interaction. Don't forget this task to be allowed to run multiple times if you want it to.

Be aware that this might generate a lot of log entries and a lot of powershell processes depending on how log your task will run.

But in most cases the solution mentioned by Mathias R. Jessen above might be the easiest one, but is also easy to be changed by any user for the session even if you changed prompt in the settings mentioned here: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles?view=powershell-7.2

Related