参数作为变量,而不是直接将文件路径传递给PowerShell cmdlet



我将文件路径存储在变量中,如下所示

$body = E:Folderbody.txt

并尝试在PowerShell脚本中的多个区域访问它,如下面的

Clear-content -$body

Get-content $body.ToString()

Set-content $body

但这三种类型的传递参数都不起作用。我在下面收到错误。

Cannot find path 'C:UsersS51-' 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:Folderbody.txt方法有效。

是否有任何方法可以为变量分配路径并在整个代码中使用它们,因为我需要多次访问同一路径&如果我将来需要修改文件路径,它需要到处修改。如果它是一个变量,我只能在一个地方进行修改。

tl;dr

  • 你的症状都可以用$body的值来解释,实际上就是$null

  • 问题是E:Folderbody.txt没有被引用;如果你引用它,你的症状就会消失:

$body = 'E:Folderbody.txt'

此答案的底部部分解释了PowerShell中的字符串文本,并解释了PowerShell的两种基本解析模式,参数(命令(模式和表达式方式。


解释:

我将文件路径存储在变量中,如下所示

$body = E:Folderbody.txt

因为您想要成为字符串E:Folderbody.txt的内容没有被引用,所以E:Folderbody.txt被解释为命令,这意味着:

  • E:Folderbody.txt作为文档打开,这意味着默认情况下,它在Notepad.exe中异步打开

  • 由于此操作没有输出(返回值(,因此使用值$null创建变量$body(严格地说,是[System.Management.Automation.Internal.AutomationNull]::Value值,在大多数情况下其行为类似于$null(。

你所有的症状都是$body的值实际上是$null的结果。

下面的代码演示了使用变量对文件进行操作的几种方法。

param(
[string] $body = "$PSScriptRootbody.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

最新更新