Reputation: 35
I store file path in variable as below
$body = E:\Folder\body.txt
And try to access it at multiple areas in a PowerShell script like below
Clear-content -$body
Get-content $body.ToString()
Set-content $body
But all these three type of passing arguments are not working. I am getting errors below.
Cannot find path 'C:\Users\S51\-' because it does not exist
You cannot call a method on a null-valued expression
Cannot bind argument to parameter 'Path' because it is null
Only the traditional
Clear/Get/Set-content E:\Folder\body.txt
methods work.
Is there any way to assign path to a variable and use them across whole code because I need to access the same path multiple times & if I need to modify the file path in future it requires to modify everywhere. If it is a variable, I can just modify at one place.
Upvotes: 1
Views: 5616
Reputation: 440337
tl;dr
Your symptoms are all explained by the value of $body
effectively being $null
.
The problem is that E:\Folder\body.txt
isn't quoted; if you quote it, your symptoms go away:
$body = 'E:\Folder\body.txt'
The bottom section of this answer explains string literals in PowerShell, and this answer explains PowerShell's two fundamental parsing modes, argument (command) mode and expression mode.
Explanation:
I store file path in variable as below
$body = E:\Folder\body.txt
Because what you intend to be string E:\Folder\body.txt
isn't quoted, E:\Folder\body.txt
is interpreted as a command, which means:
E:\Folder\body.txt
is opened as a document, which means that it is opened asynchronously in Notepad.exe
by default.
Since this operation has no output (return value), variable $body
is created with value $null
(strictly speaking, the [System.Management.Automation.Internal.AutomationNull]::Value
value, which in most contexts behaves like $null
).
All your symptoms are the result of the value of $body
effectively being $null
.
Upvotes: 1
Reputation: 9610
The code below illustrates several ways of using a variable to operate on files.
param(
[string] $body = "$PSScriptRoot\body.txt"
)
if ((Test-Path -Path $body) -eq $false) {
New-Item -Path $body -ItemType File
}
function GetContent() {
Get-Content -Path $body -Verbose
}
GetContent
function GetContentOfFile([string] $filePath) {
Get-Content -Path $body -Verbose
}
GetContentOfFile -filePath $body
Invoke-Command -ScriptBlock { Clear-Content -Path $body -Verbose }
Invoke-Command -ScriptBlock { param($filepath) Clear-Content -Path $filepath -Verbose } -ArgumentList $body
Set-content -Path $body -Value 'Some content.' -Verbose
Upvotes: 0