1

I am trying to retrieve files from a remote system via PowerShell. In order to do this i utilize New- PSSession and Invoke-Command in this session.

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

If i set path to $Path = "$env:SystemRoot\System32" it works just fine, but if i set it to a string read from a configuration file (json) it gives me the weirdest problems. One is that it cannot find the parameter -Directory, if i omit the -Directory and -Name parameters the error message is Ein Laufwerk mit dem Namen "$env" ist nicht vorhanden. Roughly translatet to A drive named "$env" is not available.

The configuration file looks like this:

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

The Powershell script is the following:

$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

1 Answer 1

1

You need to explicitely expand the string read from the Path element in the Json file.

This should do it:

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

An alternative could be by using Invoke-Expression:

$Path = Invoke-Expression ('"{0}"' -f $logConfig.File[0].Path)
Sign up to request clarification or add additional context in comments.

2 Comments

The alternative worked, it is now used like this $latestFolder = Invoke-Command -Session $remoteSession -ScriptBlock{param($path) Get-ChildItem (Invoke-Expression ('"{0}"' -f $path)) -Directory -Name} -ArgumentList $logConfig.File[0].Path
@xBarns Good to hear. The first one worked for me too in PowerShell 5.1, but I have noticed there may be quirks in other versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.