json - 从文件读取配置时,Invoke-Command 失败并显示 $env 变量失败
问题描述
我正在尝试通过 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。大致翻译为名为“$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
解决方案
您需要显式扩展从Path
Json 文件中的元素读取的字符串。
这应该这样做:
$Path = $ExecutionContext.InvokeCommand.ExpandString($logConfig.File[0].Path)
另一种方法是使用Invoke-Expression
:
$Path = Invoke-Expression ('"{0}"' -f $logConfig.File[0].Path)