0

I have some problem passing the PowerShell variables to Invoke-Command (running CMD /C). The problem is, that the $script_location parameter is empty.

My script creates a batch file on an UNC path with an unique name (20190423T1152100840Z.bat) with some commands in it. At the end, I would like to run this generated batch file on a server.

$datum = Get-Date -Format FileDateTimeUniversal
$script_location = "\\uncpath\batchfile_$datum.bat"
$Username = 'user'
$Password = 'pass'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Add-Content $script_location " preferences_manager -u=user -p=pass -target=$env:username"
Invoke-Command -ComputerName "SERVERNAME" -Credential $cred -ScriptBlock {
    Invoke-Expression -Command:"cmd /c $script_location"
}

The expected result should be that the Invoke-Command runs the $script_location batch file. Currently the result is that that the $script_location variable is empty.

Any clue on how to do that?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Nikec123
  • 39
  • 6
  • As a side-note: [do not use `Invoke-Expression`](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/). Use the call operator instead (`& $using:script_location`). – Ansgar Wiechers Apr 23 '19 at 14:03

1 Answers1

2

The easiest way to pass a variable into a ScriptBlock is by prefixing its name with the using: scope.

Invoke-Command -ComputerName "SERVERNAME" -Credential $cred -ScriptBlock {
    Invoke-Expression -Command:"cmd /c $using:script_location"
}

You can also pass it as an argument:

Invoke-Command -ComputerName "SERVERNAME" -Credential $cred -ScriptBlock {
    Param($ScriptLocation)
    Invoke-Expression -Command:"cmd /c $ScriptLocation"
} -ArgumentList $script_location
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
alroc
  • 27,574
  • 6
  • 51
  • 97