Matt616
Matt616

Reputation: 43

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?

Upvotes: 1

Views: 1391

Answers (3)

wallybh
wallybh

Reputation: 952

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

Upvotes: 1

Manuel Batsching
Manuel Batsching

Reputation: 3616

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

Upvotes: 2

Luke
Luke

Reputation: 667

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

Upvotes: 0

Related Questions