简体   繁体   English

如何在Powershell中创建带有变量和文本的文件

[英]How to make a file with a variable and text in Powershell

I can't output text with variable in double inverted commas to another file using Powershell.我无法使用 Powershell 将带有双引号中的变量的文本输出到另一个文件。 I had done it in batch and it worked but it didn't work with Powershell.我已经批量完成它并且它有效但它不适用于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.当我运行文件时,变量会丢失其值。

that is because it is a script variable.那是因为它是一个脚本变量。 There are different scopes in Powershell. Powershell 中有不同的作用域。 They are;他们是; $Private:variable , $Script:variable , $Local:variable , $Global:variable . $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 .如果要在 Powershell 终端中运行脚本后调用该变量,则需要编写$Global:name Otherwise its scope it going to be $Local to the script.否则它的范围将是脚本的$Local

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,使用转义的`"双引号(Powershell 的转义是反引号)来获取有关 $name 的引号。像这样,

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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