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

Argument as variable, instead of directly passing file path, to PowerShell cmdlets

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

但这三种传递参数都不起作用。我收到以下错误。

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 方法有效。

有什么方法可以将路径分配给变量并在整个代码中使用它们,因为我需要多次访问同一路径&如果我以后需要修改文件路径,则需要在所有地方进行修改。如果是变量,我只修改一处即可。

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

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

tl;dr

  • 您的症状全部由 $body 的值有效地解释为 $null

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

$body = 'E:\Folder\body.txt'

this answer explains string literals in PowerShell, and 的底部解释了PowerShell的两种基本解析模式,参数(命令)模式和表达式模式。


解释:

I store file path in variable as below

$body = E:\Folder\body.txt

因为你想要的是 string E:\Folder\body.txt 没有被引用, E:\Folder\body.txt被解释为命令,意思是:

  • E:\Folder\body.txt 作为文件打开,也就是说在异步打开Notepad.exe默认。

  • 因为这个操作没有输出(return值),变量$body被创建为值$null(严格来说,[System.Management.Automation.Internal.AutomationNull]::Value值,在大多数情况下其行为类似于 $null).

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