从文件中读取配置时,Invoke命令失败,$env变量失败



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

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

如果我将path设置为$Path = "$env:SystemRootSystem32",它就可以正常工作,但如果我将其设置为从配置文件(json(读取的字符串,它会给我带来最奇怪的问题。一个是它找不到参数-Directory,如果我省略-Directory和-Name参数,则错误消息为Ein-Laufwerk mit dem Namen"$env";我是尼克·沃汉登粗略翻译为一个名为"$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:SystemRootSystem32"
$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文件中的Path元素读取的字符串。

这应该做到:

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

另一种选择是使用Invoke-Expression:

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

最新更新