簡體   English   中英

如何在Powershell的“ get-content命令”中傳遞變量

[英]how to pass a variable in “get-content command ” in powershell

我必須將特定文件從一個遠程桌面獲取到本地計算機或另一台服務器。如何在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

無法將參數綁定到參數“ Path”,因為它為null。 + CategoryInfo:InvalidData:(:) [獲取內容],ParameterBindingValidationException + FullyQualifiedErrorId:ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

嘗試在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

您可以通過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

這樣做的好處是不會出現兩次跳轉的情況,盡管在其上運行命令的服務器將需要訪問任何遠程文件路徑。 如果您需要將文件從一台服務器復制到另一台服務器,但是目標服務器沒有將文件路徑顯示為共享文件夾(或者您無權訪問),則不能在-FromSession上指定-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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM