【问题标题】:Powershell test-path from variable [duplicate]来自变量的Powershell测试路径[重复]
【发布时间】:2022-01-04 16:26:31
【问题描述】:

我有一个 PowerShell 远程处理脚本,它的测试路径始终为 false。

$pathname = "C:\temp"
$hostremote = "computer122" #example

示例 - 不起作用:

Invoke-Command -ComputerName $hostremote {Test-Path -Path '$pathname' }

示例 - 工作正常:

Invoke-Command -ComputerName $hostremote {Test-Path -Path 'C:\temp' }

我尝试使用 " 并导致错误,因此将 ' 或 " 排除在外。必须是一个简单的 powershell 技巧,我因为这么简单的事情而错过了。

【问题讨论】:

  • 试试Invoke-Command -ComputerName $hostremote {Test-Path -Path $using:pathname }Invoke-Command 在远程范围内运行。局部变量在该范围内不可用。是的,不要在要扩展的变量周围使用单引号,除非那些单引号被外部双引号包围。
  • 使用命令help Invoke-Command -Full 其中Example 9 解释了using: 的使用。

标签: powershell


【解决方案1】:

有几个问题:

首先,调用变量时切勿使用单引号。如果要按原样使用变量,为什么要使用引号? -Path $pathname要简单得多。如果您想在其他内容中设置,请使用双引号 -Path "$pathname\SomeSubDir"

其次,你的变量在一个不同的范围内,所以你不能像这样检索它,所以你可以这样做

Invoke-Command -ComputerName $hostremote {Test-Path -Path $using:pathname }

但这对我来说似乎很糟糕,我更喜欢这个:

Invoke-Command -ComputerName $hostremote {Test-Path -Path $args[0] } -ArgumentList $pathname

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    相关资源
    最近更新 更多