简体   繁体   中英

How do I save a command output to a variable, and how do I use that variable as command parameter in Powershell?

I'd like to replace a word inside a .cfg file with the name of the current user.

I know $env:username outputs the current user.

This is what I got:

(Get-Content -path path\example.cfg -Raw) -replace 'TEST','current_user' | Set-Content path\example.cfg

I'm trying to replace the word "TEST" with the current user.

Just replace your literal string 'current_user' with $env:username and you're good to go:)

(Get-Content -path path\example.cfg -Raw) -replace 'TEST',$env:username | Set-Content path\example.cfg

Note that -replace is a regex operator, so we can even qualify the word we're looking for:

(Get-Content -path path\example.cfg -Raw) -replace '\bTEST\b',$env:username | Set-Content path\example.cfg

\b means "word boundary" in regex, and will help you avoid partially replacing TEST in words like "HOTTEST" or "TESTICULAR"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM