我将文件路径存储在如下变量中
$body = E:\Folder\body.txt
并尝试在PowerShell脚本中的多个区域访问它,如以下所示
Clear-content -$body
Get-content $body.ToString()
Set-content $body
但是这三种类型的传递参数都不工作。我得到的错误如下。
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
只有传统的
Clear/Get/Set-content E:\Folder\body.txt
方法工作。
有没有什么方法可以将路径分配给一个变量,并在整个代码中使用它们,因为我需要多次访问同一个路径&如果我将来需要修改文件路径,就需要到处修改。如果它是一个变量,我可以只在一个地方修改。
tl;dr
你的症状都是由 $body
实际上是 $null
.
问题是 E:\Folder\body.txt
未引用;如果你引用它,你的症状就会消失。
$body = 'E:\Folder\body.txt'
底部的部分 本回答 解释 字符串 在PowerShell中,以及 本回答 解释了PowerShell的两种基本解析模式。口令 模式和 表情 模式。
解释。
我将文件路径存储在如下变量中
$body = E:\Folder\body.txt
因为你想做的事 绳子 E:\Folder\body.txt
未引用, E:\Folder\body.txt
被解释为 指挥,这意味着。
E:\Folder\body.txt
是作为一个文件打开的意思是说,它被打开了 异步 在 Notepad.exe
缺省情况下,该操作没有输出(返回值)。
因为这个操作没有输出(返回值),所以变量 $body
是以价值创造的 $null
(严格地说,该 [System.Management.Automation.Internal.AutomationNull]::Value
值,在大多数情况下,它的行为就像 $null
).
你的所有症状都是由以下数值造成的 $body
实际上是 $null
.
下面的代码说明了使用变量对文件进行操作的几种方法。
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