1

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?

Matt616
  • 33
  • 1
  • 5
  • Why are you using `"\\args[0]\ ` instead of putting `"\\$server\" ` ? – Luke May 29 '15 at 19:16
  • @luke - I tried that first and it didn't work. Found this post to use args. http://stackoverflow.com/questions/7023012/passing-powershell-variables-into-a-scriptblock – Matt616 May 29 '15 at 19:35

3 Answers3

2

Be careful with variables in strings: "\\$args[0]\hot.war" will be expanded to \\MyServerName[0]\hot.war.

Use "\\$($args[0])\hot.war" to be sure that $args[0] will be treated as a single expression.

See: http://blogs.msdn.com/b/powershell/archive/2006/07/15/variable-expansion-in-strings-and-herestrings.aspx

Manuel Batsching
  • 3,406
  • 14
  • 20
1

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
wallybh
  • 934
  • 1
  • 11
  • 28
0

You will want to add the server variable into your first line...

$server = "MyServerName"

$lastWrite = Invoke-Command -Computername $server -ScriptBlock {Get-ChildItem "\\$server\hot.war" } -argumentlist $server | select -Property LastWriteTime
Luke
  • 647
  • 1
  • 8
  • 22
  • That's where I had begun but it doesn't work. Cannot find path '\\\\hot.war' because it does not exist. [link]http://stackoverflow.com/questions/7023012/passing-powershell-variables-into-a-scriptblock – Matt616 May 29 '15 at 19:31