简体   繁体   English

在Powershell中将参数传递给远程命令

[英]Passing an argument to remote command in Powershell

Using Powershell I want to create a directory on a remote computer with the current time stamp in its name. 我想使用Powershell在远程计算机上创建一个目录,并在其名称中使用当前时间戳。 After setting up remoting and the variables that I need, this is easy to achieve for me, eg: 设置了远程处理和所需的变量之后,这对我来说很容易实现,例如:

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

Now I would like to retrieve the date on the local machine like 现在我想在本地机器上检索日期

$currentDateTime = get-date -f yyyyMMddhhmmss

and then use that variable to create and, later on, refer to such a directory remotely, eg for copying files into it, like: 然后使用该变量创建,以后再远程引用该目录,例如用于将文件复制到其中,例如:

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

The first line does not work since the variable does not seem to be known in the script context, so I also don't know whether the second line would work if I get the first one done. 第一行不起作用,因为在脚本上下文中似乎不知道该变量,因此,我也不清楚如果完成第一行后第二行是否会起作用。

As an alternative, I would also be happy (actually: prefer) to create the directory from the local machine as follows 或者,我也很乐意(实际上是:更喜欢)从本地计算机创建目录,如下所示

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

This seems to fail cause of missing credentials, but the -Credential switch does not seem to be supported for this command (?). 这似乎由于缺少凭据而失败,但是此命令(?)似乎不支持-Credential开关。

How do you create such a folder on the remote machine? 您如何在远程计算机上创建这样的文件夹? (I need to do this with version 2.0 of Powershell) (我需要使用Powershell 2.0版来执行此操作)

Powershell don't know the variabel in the invoke command. Powershell在invoke命令中不知道variabel。 With the -ArgumentList you can pass it into the invoke command. 使用-ArgumentList ,可以将其传递给invoke命令。
Look at the example, do this work for you? 查看示例,这对您有用吗?

$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

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

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