【问题标题】:Argument as variable, instead of directly passing file path, to PowerShell cmdlets参数作为变量,而不是直接将文件路径传递给 PowerShell cmdlet
【发布时间】:2020-05-09 07:23:19
【问题描述】:

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

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

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

【问题讨论】:

  • 不确定,但我想你想看看Scopes。可能,您想将路径变量声明为$global:ThePathVariable
  • 首先,它看不到您的文件路径-您应该使用Clear-Content -Path $body,是的,如果它使用不同的路径,那么您可能需要定义$body,范围更广,例如$Script:body = E:\Folder\body.txt

标签: powershell powershell-cmdlet


【解决方案1】:

tl;dr

  • $body 的值实际上是 $null

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

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

this answer 的底部部分解释了 PowerShell 中的 字符串文字this answer 解释了 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 的结果。

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2016-03-03
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多