Search code examples
batch-filememorytemp

Creating "Memory" In Batch Files


I'm not sure how to word my question here. But for example, say I have a batch file with:

@echo off

echo test > text.txt
set example_var=<text.txt

I know that this specific piece of code is redundant since you could just set "example_var" equal to "test", but my question is how can I create "memory" (as in data that the text document holds) inside of the batch?

Something like this:

@echo off

echo test 0>&1
set example_var=<&1

Basically I just want to avoid creating temporary text documents to hold information. I am sure I found an example on this website before but I couldn't find it.

EDIT:

So this is the situation:

(%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe .\Code.ps1) | find "::/kl" | set /p code

I want the output of %systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe .\Code.ps1 and find "::/kl" to be the input for set /p code, ultimately setting a string of text to be put into the variable code.


Solution

  • Your pipe approach will fail to set the variable for the current script because each of the commands in the pipe are running in separate processes.

    The usual way to deal with the task of retrieving the output of a command into a variable is to use a for /f command

    for /f "delims=" %%a in ('
        %systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe .\Code.ps1
        ^| find "::/kl"
    ') do set "code=%%a"