1

I can't output text with variable in double inverted commas to another file using Powershell. I had done it in batch and it worked but it didn't work with Powershell.

Example:

$name = Read-host -prompt "Enter your name" echo {Your name is "$name"} >name.txt pause 

When I run the file the variable loses its value.

3 Answers 3

2

that is because it is a script variable. There are different scopes in Powershell. They are; $Private:variable, $Script:variable, $Local:variable, $Global:variable.

If you want to call the variable after you have run the script with in the Powershell terminal you need to write $Global:name. Otherwise its scope it going to be $Local to the script.

Sign up to request clarification or add additional context in comments.

Comments

1

This is caused, as a new script block is being created. Since there's not much actual content in the script block, it will return its content to the pipeline as a string.

As a side note, the "double inverted commas" are usually called "double quotes". Using proper name makes it easier to google for advice.

Resolution is to get rid of the script block. Use escaped `" double quote (Powershell's escape is the backtick) to get quotes about $name. Like so,

$name = Read-host -prompt "Enter your name" write-host "Your name is `"$name`"" >name.txt 

Comments

0

you may try:

$destination="C:\test\File2.txt" $name=Read-Host -Prompt "Enter your name" Set-Content -Path $destination -Value $name Start-Sleep -Seconds 5 

If you still want to stick to your code:

$name = Read-host -prompt "Enter your name" echo "Your name is $name" >name.txt pause 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.