2

I'm running powershell script with batch file.

My requirement is:-

  1. display the output in batch cmd and at the same time save output in TXT file. Note, as of now output getting saved in txt file but output is not visible in batch cmd.
  2. Create a folder with system serial number in C drive and save txt file in that folder.

Batch File name:- Check.bat

Powershell script name:- Check.ps1 (powershell file contains bulk commands which output will be displayed in batch file as a command prompt)

Batch file code:-

@echo off
for /F %%a in ('wmic bios get serialnumber') do call :Sub %%a
:Sub
if not "%*"=="" set SerialNumber=%*

xcopy "%~dp0*" "C:\windows\Temp\Compliance_Check" /q /s /e /y /i
PowerShell.exe -ExecutionPolicy Bypass -File %~dp0Compliance_Check.ps1 > C:\%SerialNumber%\output.txt
pause
1
  • 1
    The best move is to alter your Compliance_Check.ps1 because powershell can easily capture the output of any command into a variable, and from there you can output the variable to screen and also save it to a file. For example: $command = .\program.exe; write-host $command; $command | out-file -append "log.txt"
    – LPChip
    Nov 23, 2022 at 20:16

1 Answer 1

2

UPDATED RESPONSE

The batch file becomes:

PowerShell.exe -ExecutionPolicy Bypass -File %~dp0Check.ps1
pause

And, using Tee-Output which takes the output of the previous command in the pipeline and sends it both to a file and to the next command in the pipeline, the PowerShell will be something like:

$serialNumber = Get-WmiObject -Class Win32_BIOS | Select-Object -ExpandProperty SerialNumber
$logFilePath = "C:\$serialNumber\posh.log"
if (-not (Test-Path -Path (Split-Path -Path $logFilePath -Parent))) { md $logFilePath }
if (Test-Path -Path $logFilePath) { Remove-Item -Path $logFilePath }

Copy-Item -Path 'C:\test\source\*' -Destination 'C:\test\Temp\Check' -Recurse -Force | Tee-Object -FilePath $logFilePath

Get-Date | Tee-Object -FilePath $logFilePath -Append

Get-ChildItem -Path 'C:\test\Temp\Check' -Recurse | Tee-Object -FilePath $logFilePath -Append

You need to use -Append on Tee-Output after the first time, if you want it all in the same file.

This might not meet your exact requirements but you've edited the question substantially twice since I started trying to answer it and I'm out of time.

4
  • 1
    I see you've edited your question since I wrote that. I think it would be easier to do everything in PowerShell. Nov 23, 2022 at 19:09
  • How we can do that in powershell? Nov 23, 2022 at 19:19
  • Now I have 1 query, where do I need to paste this code in PowerShell (at the beginning or at the end?) Nov 23, 2022 at 19:37
  • The lines up to and including Copy-Item are the necessary bits and would go at the top of your PowerShell script. The other bits were just examples to show you how to use -Append on subsequent commands. Nov 23, 2022 at 19:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .