简体   繁体   English

使用输出运算符在powershell中命名.txt文件

[英]Naming a .txt file in powershell using output operator

I am trying to create a variable that will name a text file using the output operator in powershell. 我正在尝试创建一个变量,它将使用powershell中的输出运算符命名文本文件。 The first example is what would normally be done without the variable (which works), and the second is going to be the way that I am trying to do it (which is not working). 第一个例子是通常在没有变量(有效)的情况下完成的事情,第二个例子是我尝试这样做的方式(它不起作用)。

Example I: 例I:

"hello" >> janice.txt

As we can see, the result of Example I would be a text file called janice.txt 我们可以看到,示例I的结果将是一个名为janice.txt的文本文件

Example II. 例II。

$i = "janice"
"hello" >> $i.txt

The result that I would expect from example II would be a text file named: janice.txt just like the first example since the variable $i is storing the string "janice". 我期望从示例II得到的结果将是一个名为:janice.txt的文本文件,就像第一个示例一样,因为变量$ i存储字符串“janice”。

Powershell is executing the command with no errors, but no .txt file is created. Powershell正在执行命令而没有错误,但没有创建.txt文件。 I'm trying to figure out why It's not working and if anything, is it completely irrelevant. 我试图弄清楚为什么它不起作用,如果有的话,它是完全无关紧要的。

This is my first time asking a question so I apologize in advance if it is wordy and rather vague. 这是我第一次提出问题,所以如果它是罗嗦而且含糊不清,我会事先道歉。

Obvious after someone else pointed it out to me; 别人向我指出之后显而易见; $i.txt is doing a property lookup. $i.txt正在进行属性查找。 Like $i.Length or $file.FullName . $i.Length$file.FullName

Since there is no property called .txt , the lookup returns $null and your write goes nowhere like doing "hello" > $null . 由于没有名为.txt属性,因此查找返回$null并且您的写入无处可执行"hello" > $null

Proof: Running the PowerShell tokenizer against the two pieces of code to see how they are processed internally: 证明:针对这两段代码运行PowerShell tokenizer,以了解它们在内部的处理方式:

[System.Management.Automation.PSParser]::Tokenize('"a" > janice.txt', [ref]$null)  | 
    Select-Object Content, Type |
    Format-List


Content : a
Type    : String

Content : >
Type    : Operator

Content : janice.txt
Type    : CommandArgument

A redirect operator, with a string on the left and a command argument on the right. 重定向运算符,左侧是字符串,右侧是命令参数。 Vs. 比。

[System.Management.Automation.PSParser]::Tokenize('"a" > $i.txt', [ref]$null) |
    Select-Object Content, Type |
    Format-List


Content : a
Type    : String

Content : >
Type    : Operator

Content : i
Type    : Variable

Content : .
Type    : Operator

Content : txt
Type    : Member

A string and a redirect operator, with (a variable, the . operator and 'txt' as a member) on the right. 字符串和重定向运算符,右侧是(变量, .运算符和'txt'作为成员)。

Try this: 尝试这个:

"hello" >> "$i.txt"

:) :)

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

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