简体   繁体   English

Powershell在ScriptBlock中传递参数

[英]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? 任何人都可以帮助完成第一组工作吗?

Be careful with variables in strings: "\\\\$args[0]\\hot.war" will be expanded to \\\\MyServerName[0]\\hot.war . 注意字符串中的变量: "\\\\$args[0]\\hot.war"将扩展为\\\\MyServerName[0]\\hot.war

Use "\\\\$($args[0])\\hot.war" to be sure that $args[0] will be treated as a single expression. 使用"\\\\$($args[0])\\hot.war"确保$args[0]将被视为单个表达式。

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

Another way, if you are using PowerShell 3. You can do something like this: 另一种方法,如果您使用的是PowerShell 3.您可以执行以下操作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM