【问题标题】:how to pass a variable in "get-content command " in powershell如何在powershell的“get-content command”中传递变量
【发布时间】:2019-12-30 07:01:06
【问题描述】:

我必须从一个远程桌面获取特定文件到本地计算机或另一台服务器。如何在 get-content 中传递一个变量以从远程桌面连接获取文件?

我将文件路径存储为变量并尝试在 get-content 中传递它。

Invoke-Command -Computername $Server -ScriptBlock{get-content -path $file }
Invoke-Command -Computername $Server -ScriptBlock{get-content -path ${file} }

$file="C:\Users\Documents\new DB_connection\\log2.txt"

 $Server="servername"

 $answer=  Invoke-Command -Computername $Server -ScriptBlock{get-content -path $file } 
write-output $answer

无法将参数绑定到参数“路径”,因为它为空。 + CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

【问题讨论】:

  • 我试过这段代码 "Invoke-Command -Computername $Server -ScriptBlock{get-content -path $file } 但它再次显示同样的错误
  • 一旦你给$file赋值,然后在脚本块内简单地使用$using:file。在定义之前,您不能将其传递到脚本块中

标签: powershell


【解决方案1】:

您可以通过 PSSession 复制文件,而不是使用 Invoke-Command。从远程服务器复制到本地路径或不同的远程服务器:

 $session = New-PSSession -ComputerName server.domain.tld
 Copy-Item -Source $originatingServerFilePath -Destination $localOrUNCFilePath -FromSession $session

如果您需要将本地文件复制到目标服务器:

Copy-Item -Source $localFilePath -Destination $destinationServerFilePath -ToSession $session

虽然您运行该命令的服务器需要访问任何远程文件路径,但这样做的好处是不进行双跳。如果您需要将文件从一台服务器复制到另一台服务器,但目标服务器没有将文件路径公开为共享文件夹(或者您无权访问它),则不能指定 -ToSession-FromSession同时,因此您必须在本地复制文件并使用两个会话,如下所示:

$sourceSession = New-PSSession -ComputerName source.domain.tld
$destinationSession = New-PSSession -ComputerName destination.domain.tld

# Copy the remote file(s) from the source session to a local path first
Copy-Item -Source $sourceSessionFilePath -Destination $localTempFilePath -FromSession $sourceSession

# Copy the new local files to the destination session from your local path
Copy-Item -Source $localTempFilePath -Destination $destinationSessionFilePath -ToSession $destinationSession

【讨论】:

    【解决方案2】:

    尝试在ScriptBlock

    中定义变量
    $Server="servername"
    $answer=  Invoke-Command -Computername $Server -ScriptBlock{
    $file="C:\Users\Documents\new DB_connection\\log2.txt";
    get-content -path $file} 
    write-output $answer
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多