【问题标题】:Passing an argument to remote command in Powershell在 Powershell 中将参数传递给远程命令
【发布时间】:2014-08-26 08:43:35
【问题描述】:

使用 Powershell 我想在远程计算机上创建一个目录,其名称中包含当前时间戳。在设置远程处理和我需要的变量之后,这对我来说很容易实现,例如:

Invoke-Command -ComputerName $server -credential $Cred -ScriptBlock {New-Item -ItemType Directory c:\tmp\$(get-date -f yyyyMMddhhmmss)}

现在我想在本地机器上检索日期

$currentDateTime = get-date -f yyyyMMddhhmmss

然后使用该变量创建并稍后远程引用这样的目录,例如用于将文件复制到其中,例如:

Invoke-Command -ComputerName $server -credential $Cred -ScriptBlock {New-Item -ItemType Directory c:\tmp\$currentDateTime}
....(20 secs later)....
copy file \\$server\C$\tmp\$currentDateTime

第一行不起作用,因为在脚本上下文中似乎不知道该变量,所以我也不知道如果我完成第一行,第二行是否会起作用。

作为替代方案,我也很乐意(实际上:更喜欢)从本地计算机创建目录,如下所示

New-Item -Path \\$server\C$\tmp\$currentDateTime

这似乎因缺少凭据而失败,但此命令似乎不支持 -Credential 开关 (?)。

如何在远程机器上创建这样的文件夹? (我需要用 2.0 版的 Powershell 来做这个)

【问题讨论】:

  • 在我的带有 powershell V2.0 的服务器上,我在 New-Item 有 -Credential 开关。

标签: powershell remote-access


【解决方案1】:

Powershell 不知道调用命令中的变量。使用-ArgumentList,您可以将其传递给调用命令。
看看这个例子,这对你有用吗?

$datCurrentDate = Get-Date -Format "yyyyMMddhhmmss"
$strFolderPath = "\\servername\c$\temp\$($datCurrentDate)_Foldername"

$scbScriptBlock = {
    $strFolderPath = $args[0]    
    New-Item -ItemType Directory -Path $strFolderPath 
}

Invoke-Command -ComputerName $server -credential $Cred -ScriptBlock $scbScriptBlock -ArgumentList $strFolderPath
....(20 secs later)....
copy file $strFolderPath

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 2014-06-14
    相关资源
    最近更新 更多