Search code examples
powershellinvoke-commandscriptblock

Powershell passing arguments in ScriptBlock


I'm trying to get the last write time on a file from a remote server.

This doesn not work:

$server = "MyServerName"

$lastWrite = Invoke-Command -Computername $server -ScriptBlock {Get-ChildItem "\\$args[0]\hot.war" } -argumentlist $server | select -Property LastWriteTime

This does work:

 $lastWrite = Invoke-Command -Computername $server -ScriptBlock {Get-ChildItem "\\MyServerName\hot.war" } -argumentlist $server | select -Property LastWriteTime

Can anyone help make the first set work?


Solution

  • Another way, if you are using PowerShell 3. You can do something like this:

    $lastWrite = Invoke-Command -Computername $server -ScriptBlock {
                   Get-ChildItem "\\$using:server\hot.war"
                 } | select -Property LastWriteTime