There is a file, the task is to transfer this file to another computer via powershell + C # it is necessary to transfer it in parts, 1kb each

I do this: I read a piece of the file into an array of bytes, then convert this array to a string, and write the file to the file via the Add-Content cmdlet, but I have several times more output file, as if I copy the first piece first, then the first one is written + second, then first is added + second + third, etc. Moreover, I debazhil watched every read line, it is normal, not to say that each subsequent combines the previous one. If I use the Set-Content cmdlet, then of course in the output in the file is the last piece. Tell me, please, where is my mistake

using (PowerShell ps = PowerShell.Create()) { using (FileStream fs = new FileStream(configuration.FilePath, FileMode.Open, FileAccess.Read)) { int chunkSize = 1024; byte[] buffer = new byte[chunkSize]; while (true) { int readed = fs.Read(buffer, 0, chunkSize); if (readed == 0) break; string fileChunk = Convert.ToBase64String(buffer, 0, readed); string script = @" $Username = '" + configuration.Login + @"' $Password = '" + configuration.Password + @"' $SecurePass = ConvertTo-SecureString -AsPlainText $Password -Force $Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$SecurePass $DataDecoded = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('" + fileChunk + @"')) Invoke-Command {$using:DataDecoded | Add-Content -Path C:\Test\Script1.ps1} -ComputerName " + configuration.Ip + @" -Credential $Cred "; ps.AddScript(script); ps.Invoke(); } } } } 
  • In my opinion, you do not exhibit a shift in the method Read - Vadim Bondaruk
  • Well, in the same place, the carriage moves like an automatic - Alex
  • @VadimBondaruk, there the offset for the buffer is set. - free_ze

1 answer 1

Found a mistake, maybe someone will come in handy

I constantly ran the script in one Powershell session, rearranged PowerShell.Create () just before the script and everything started to add normally, although now there’s another problem: it inserts a new piece from a new line even if it is a continuation of the previous one ((Is it possible to correct this?