- [C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform
- [C#] Hướng dẫn viết ứng dụng chat với Gemini AI Google Winform
- Hướng dẫn khóa file bằng nhiều process id, không cho xóa tập tin
- Hướng dẫn cách tạo Product Id cho ứng dụng phần mềm XXXXX-XXXXX-XXXXX-XXXXX
- [SQLSERVER] Hướng dẫn tạo script sql từ ứng dụng Sqlserver management Studio
- [C#] Hướng dẫn sử dụng thư viện AutoITx lấy id và password Ultraviewer trên winform
- [VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator
- [C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng
- [DEVEXPRESS] Chia sẻ source code tạo báo cáo report in tem nhãn label trên C# winform
- [DEVEXPRESS] Hướng dẫn vẽ biểu đồ Bar Chart trên Winform
- [C#] Tạo form đăng nhập và đăng ký với hiệu ứng Sliding Animation Effect
- [C#] Hướng dẫn tạo thanh toán đơn hàng qua mã vạch VietQR sử dụng API PayOS hoàn toàn miễn phí
- [C#] Hướng dẫn ghi log ra RichTextBox giống Console trên Winform sử dụng thư viện Serilog
- [C#] Hướng dẫn cách tạo mã QR Code trên file Excel
- [VB.NET] Gởi tin nhắn và file đính kèm qua ứng dụng gởi tin nhắn Whats App
- [C#] Viết ứng dụng Auto Fill list Textbox from clipboard Winform
- [TOOL] Chia sẻ phần mềm thay đổi thông tin cấu hình máy tính
- [C#] Hướng dẫn Export dữ liệu ra file Microsoft Word Template
- [C#] Chia sẻ source code tool kiểm tra domain website
- [C#] Hướng dẫn tạo file PDF sử dụng thư viện QuestPDF
Download và Giải nén tập tin File sử dụng Powershell
Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách Download và giải nén tập tin File với Power Shell trong Windows.
[POWER SHELL] DOWNLOAD AND EXTRACT FILE RAR
Mình ví dụ, công việc bạn muốn thực hiện như sau:
Bước 1: Mình download tập tin file Rar từ Internet về địa chỉ Local ở máy mình.
Bước 2: Giải nén tập tin File đó ra ở đường dẫn mình chỉ định.
Bước 3: Xóa tập tin vừa download
Thay vì, các bạn thao tác bằng tay thủ công để download và giải nén, các bạn có thể viết thành một Script Powershell để chỉ cần 1 nút nhấn Click là hoàn thành công việc trên.
Dưới đây là demo của mình tải File và giải nén file sử dụng Power Shell.
I. Download File (Tải dữ liệu File)
1.Tải file có hiển thị Progress Bar sử dụng lớp [System.Net.HttpWebRequest]
Với cách tải này trên Window Power Shell ISE thì chạy nhanh nếu bạn chạy Script thì truyền vào là SlientlyContunue nhé.
$ProgressPreference = 'Continue' hoặc SilentlyContinue
function Download-File($url, $targetFile)
{
$uri = New-Object "System.Uri" "$url"
$request = [System.Net.HttpWebRequest]::Create($uri)
$request.set_Timeout(15000) #15 second timeout
$response = $request.GetResponse()
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
$responseStream = $response.GetResponseStream()
$targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $targetFile, Create
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
while ($count -gt 0)
{
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
Write-Progress -activity "Downloading file '$($url.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength) * 100)
}
Write-Progress -activity "Finished downloading file '$($url.split('/') | Select -Last 1)'"
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
Và khi muốn download file các bạn chỉ cần truyền tham số url và địa chỉ lưu trữ ở cú pháp dưới đây.
Download-File "https://down.freedesignfile.com/upload/downloads/2013/10/27/Colorful%20Fireworks%20Effect%20psd%20graphic.rar" "C:UsersNGUYENTHAODesktopNew folder (2)meomeo.rar"
2. Bạn sử dụng Module BitsTransfer để tải tập tin về
$url = "https://down.freedesignfile.com/upload/downloads/2013/10/27/Colorful%20Fireworks%20Effect%20psd%20graphic.rar"
$output = "C:UsersNGUYENTHAODesktopNew folder (2)meomeo.rar"
$temp = "C:UsersNGUYENTHAODesktopNew folder (2)"
$start_time = Get-Date
Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $output
#OR
Start-BitsTransfer -Source $url -Destination $output -Asynchronous
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
Kết quả khi chạy lệnh dưới đây:
II. Giải nén tập tin File RAR sau khi download về.
Đầu tiên, các bạn tạo hàm Extract-WinRarFiles giải nén file:
Function Extract-WinRarFiles
{
[cmdletbinding()]
Param
(
[Parameter(HelpMessage='Enter the local path to the unrar.exe program')]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path -Path $_ })]
[Alias('UREP')]
$UnRarExePath = "$env:ProgramFilesWinRARUnRAR.exe",
[Parameter(Mandatory = $true,
HelpMessage='Enter the local file path where the WinRar files are located that you would like to extract')]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path -Path $_ })]
[Alias('URSP')]
$UnRarSourcePath,
[Parameter(Mandatory = $true,
HelpMessage='Enter the local file path location you wish to extract the content to')]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path -Path $_ })]
[Alias('URTP')]
$UnRarTargetPath,
[Parameter(HelpMessage='Use this parameter to open the directory the extracted files are located in')]
[ValidateNotNullOrEmpty()]
[Alias('OTL')]
[switch]$OpenTargetLocation,
[Parameter(HelpMessage='Use this parameter to delete the original RAR files to help save disk space')]
[ValidateNotNullOrEmpty()]
[Alias('DSRF')]
[switch]$DeleteSourceRarFiles
)
Begin
{
$NewLine = "`r`n"
$RarFilePaths = (Get-ChildItem -Path $UnRarSourcePath -Recurse | Where-Object -FilterScript { $_.extension -eq '.rar' }).FullName
$RarFileSourceCount = $RarFilePaths.Count
}
Process
{
$NewLine
Write-Output -Verbose "Total RAR File Count: $RarFileSourceCount"
$NewLine
Write-Output -Verbose "Beginning extraction, please wait..."
Start-Sleep -Seconds 5
Foreach ($FilePath in $RarFilePaths)
{
&$UnRarExePath x -y $FilePath $UnRarTargetPath
}
$RarFileTargetCount = (Get-ChildItem -Path $UnRarTargetPath).Count
If ($RarFileTargetCount -eq $RarFileSourceCount)
{
Clear-Host
$NewLine
Write-Output -Verbose "$RarFileTargetCount RAR files have been extracted"
$NewLine
}
Else
{
$NewLine
Write-Warning -Message "$RarFileTargetCount out of $RarFileSourceCount have been extracted"
$NewLine
}
}
End
{
Switch ($PSBoundParameters.Keys)
{
{ $_ -contains 'OpenTargetLocation' }
{
$NewLine
Write-Output -Verbose 'Opening RAR target location...'
Start-Sleep -Seconds 5
Invoke-Item -Path $UnRarTargetPath
}
{ $_ -contains 'DeleteSourceRarFiles' }
{
$NewLine
Write-Output -Verbose 'Deleting source RAR files and the directory...'
Start-Sleep -Seconds 5
Remove-Item -Path $UnRarSourcePath -Recurse -Force
}
}
}
}
Khi giải nén tập tin chúng ta sử dụng như sau:
Extract-WinRarFiles -UnRarSourcePath "C:UsersNGUYENTHAODesktopNew folder (2)meomeo.rar" -UnRarTargetPath "C:UsersNGUYENTHAODesktopNew folder (2)" -DeleteSourceRarFiles
tham số -DeleteSourceRarFiles
dùng để xóa nguồn khi giải nén dữ liệu xong.
Thanks for watching!