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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With