I am trying to create a command that can write command definitions into a file, while also defining them. So I want a command \teecommand that takes one argument. This argument should be written to a file as is, and also expanded.
My current attempt is:
\documentclass{memoir}
\newwrite\commandsfile
\immediate\openout\commandsfile=commands.tex
\DeclareDocumentCommand\teecommand{s m}{%
\write\commandsfile{\unexpanded{#2}}%
\IfBooleanTF{#1}{}{#2} % Only expand the command if no * is given
}
\teecommand{\newcommand{\foo}{this is foo}}
\teecommand{\newcommand{\foobar}[1]{this is bar: #1}}
\begin{document}
\foo\
\foobar{123}
\end{document}
The output looks like this, as expected:

The file commands.tex is also created, with the following content:
\newcommand {\foo }{this is foo}
\newcommand {\foobar }[1]{this is bar: ##1}
The first line is as expected, but the second line has a doubled up #. This unfortunately breaks the application trying to parse the .tex file (the MathJax based equation previewer from LaTeX Workshop).
Question: How can I fix the command \teecommand to give me the correct output with #1 instead of ##1 for argument placeholders?
Note: I am using memoir in the example above as this is what I need to use in my actual document, and I want to avoid having a solution that is incompatible with it.