Reputation: 41
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.
Upvotes: 2
Views: 241
Reputation: 28993
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.
Upvotes: 5