![](/img/trans.png)
[英]Create Remote Powershell Session and load modules in Runspace using C#
[英]Copy file during remote powershell session c# runspace
我需要使用 powershell 將文件從 Azure VM 上的某個位置復制到我的本地計算機。 例如,虛擬機上的 C:\\tmp 到我本地機器上的 C:\\tmp
該應用程序是使用系統自動化的 c#。 目前我使用該方法。
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline(//Some SQL that pulls files from database to C:\tmp);
var results = pipeline.Invoke();
}
我目前使用的 powershell 只是為每個文件返回 get-content,在循環中將其返回給 c#,每次寫入文件。 然而,這是非常低效的。
這是正確的想法,但是在執行此操作時將文件分塊更有效。 Powershell 目前沒有本地方式來執行此操作,因此您必須編寫一些代碼。 有兩個部分,遠程 powershell 部分用於將服務器上的文件分塊,C# 部分用於重新組裝塊並執行 powershell。
遠程powershell部分:
$streamChunks = New-Object System.Collections.Generic.List[byte[]]
$buffer = New-Object byte[] 1024
[IO.FileStream] $fileStream = $null
try
{
$targetPath = # FILE TO GET
$fileStream = [IO.File]::OpenRead($targetPath)
[int] $bytesRead = 0
while (($bytesRead = $fileStream.Read($buffer, 0, 1024)) -gt 0)
{
$chunk = New-Object byte[] $bytesRead
[Array]::Copy($buffer, $chunk, $bytesRead)
$streamChunks.Add($chunk)
}
Write-Output $streamChunks
}
finally
{
if ($fileStream -ne $null)
{
$fileStream.Dispose()
$fileStream = $null
}
};
請注意,此腳本將由本地計算機上的運行空間調用:
Pipeline pipeline = runspace.CreatePipeline(command); // command is powershell above
Collection<PSObject> results = pipeline.Invoke();
重新組裝塊的 C# 部分:
using (FileStream fileStream = new FileStream(localPath, FileMode.OpenOrCreate, FileAccess.Write))
{
foreach (PSObject result in results)
{
if (result != null)
{
byte[] chunk = (byte[])result.BaseObject;
if (chunk != null)
{
fileStream.Write(chunk, 0, chunk.Length);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.