2

I am trying to create a variable that will name a text file using the output operator in 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:

"hello" >> janice.txt

As we can see, the result of Example I would be a text file called janice.txt

Example 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".

Powershell is executing the command with no errors, but no .txt file is created. 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.

2 Answers 2

5

Obvious after someone else pointed it out to me; $i.txt is doing a property lookup. Like $i.Length or $file.FullName.

Since there is no property called .txt, the lookup returns $null and your write goes nowhere like doing "hello" > $null.

Proof: Running the PowerShell tokenizer against the two pieces of code to see how they are processed internally:

[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.

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

1 Comment

Nice method to know for diagnostics!
4

Try this:

"hello" >> "$i.txt"

:)

2 Comments

The parentheses aren't necessary, the double quotes suffice. (To expand $var.property inside a string you've to use "$($var.property).txt"
Eureka! Makes perfect sense now, thank you very much :0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.