【问题标题】:Invoke-Command fails with $env Variable fails when configuration is read from a file从文件中读取配置时,Invoke-Command 失败并显示 $env 变量失败
【发布时间】:2020-07-23 20:35:09
【问题描述】:

我正在尝试通过 PowerShell 从远程系统检索文件。为了做到这一点,我在这个会话中使用了 New-PSSession 和 Invoke-Command。

$latestFolder = Invoke-Command -Session $remoteSession -ScriptBlock{param($path) Get-ChildItem $path -Directory -Name} -ArgumentList $path

如果我将路径设置为$Path = "$env:SystemRoot\System32",它工作得很好,但如果我将它设置为从配置文件 (json) 读取的字符串,它会给我带来最奇怪的问题。一是它找不到参数-Directory,如果我省略-Directory 和-Name 参数,错误消息是Ein Laufwerk mit dem Namen "$env" ist nicht vorhanden。 strong> 大致翻译为名为“$env”的驱动器不可用。

配置文件如下所示:

{
    "File": [
        {
            "Name": "TEST",
            "Active": true,
            "Path": "$env:SystemRoot\\System32"
        }
    ]
}

Powershell 脚本如下:

$logFilePath = Join-Path (get-item $PSScriptRoot).FullName "Test.json"
$logConfig = Get-Content -Path $logFilePath | ConvertFrom-Json

$windowsUser = "username"
$windowsUserPassword = "password"
$windowsUserPasswordsec = $windowsUserPassword | ConvertTo-SecureString -AsPlainText -Force
$Server = "server"

$Path = "$env:SystemRoot\System32"
$Path = $logConfig.File[0].Path

$sessioncred = new-object -typeName System.Management.Automation.PSCredential -ArgumentList $windowsUser, $windowsUserPasswordsec
$remoteSession = New-PSSession -ComputerName $Server -Credential $sessioncred -Authentication "Kerberos"

$latestFolder = Invoke-Command -Session $remoteSession -ScriptBlock{param($path) Get-ChildItem $path -Directory -Name} -ArgumentList $Path
$latestFolder

【问题讨论】:

    标签: json powershell invoke-command


    【解决方案1】:

    您需要显式扩展从 Json 文件中的 Path 元素读取的字符串。

    应该这样做:

    $Path = $ExecutionContext.InvokeCommand.ExpandString($logConfig.File[0].Path)
    

    另一种方法是使用Invoke-Expression

    $Path = Invoke-Expression ('"{0}"' -f $logConfig.File[0].Path)
    

    【讨论】:

    • 替代方法奏效了,现在像这样使用$latestFolder = Invoke-Command -Session $remoteSession -ScriptBlock{param($path) Get-ChildItem (Invoke-Expression ('"{0}"' -f $path)) -Directory -Name} -ArgumentList $logConfig.File[0].Path
    • @xBarns 很高兴听到。第一个在 PowerShell 5.1 中也适用于我,但我注意到其他版本中可能存在怪癖。
    猜你喜欢
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多