Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log the PowerShell commands that were run

Tags:

powershell

I am new to PowerShell so this is probably obvious or I am barking up the wrong tree with my approach. But searching on here and Google have not helped me (maybe searching for the wrong terminology?)

I am trying to write a simple PowerShell script (which works/runs no problem). However, I also have a requirement to log the process (the commands run and any output) to a txt file which I am struggling to achieve. I have tried to use the start-transcript and add the -verbose common parameter, but it is not working as I would expect.

My end goal is for the script to run on one of our servers which will stop a service, stop any related processes for the service, and then start the service again. But for this example of not being able to log what is happening I have simplified it to just starting and stopping a process. My example is below:

Start-Transcript -path "C:\tester.txt" 

Write-Host "starting the shell command"

Start-Process notepad -verbose
Start-Sleep -s 5
Stop-Process -processname notepad -verbose

Stop-Transcript

The script runs, Notepad opens, waits for 5 seconds, and then closes again. However, the verbose output is only created for the stop-process command which results in only the write-host message and the stop-process being written to my transaction/logfile. However I need it to write to my file that the Notepad process was started and then stopped.

like image 360
Jonny_Bravo Avatar asked Jan 04 '17 13:01

Jonny_Bravo


1 Answers

The below script will give you what you are asking for:

I have added comments in the script itself on each phase for better understanding. You can add a Logfile.txt check if it exists or not, based on that you can also create the file. Get-History will give you the history of all the commands which have been executed on the shell.

$Log_File= "E:\LogFile.txt"

Clear-History
# You can do a file check using Test-Path followed by the path

## Out-file will give the output to the file, -Force will create the file if not existed and -append will append the data.
"starting the shell command" | Out-File $Log_File -Force -Append

Start-Process notepad -verbose

"Notepad started" | Out-File $Log_File -Append

Start-Sleep -s 5
Stop-Process -processname notepad -verbose

"Notepad stopped" | Out-File $Log_File -Force -Append

"List of commands which are executed are below: " | Out-File $Log_File -Force -Append
Get-History | Out-File $Log_File -Append

Sample File OUTPUT:

Sample file output is attached as screenshot:

For Remote Execution:

Get-Process -Name notepad -ComputerName SERVER01 | Stop-Process

Note: There are multiple ways to stop the service remotely. Go through PowerShell Remoting and see the details.

like image 56
Ranadip Dutta Avatar answered Nov 15 '22 07:11

Ranadip Dutta