- [C#] Hướng dẫn lưu tất cả hình ảnh từ File Excel vào thư mục window
- [DATABASE] Hướng dẫn import và export hình ảnh image từ Sqlserver
- [DATABASE] Hướng dẫn sử dụng Hàm ASCII trong sqlserver
- [C#] Hướng dẫn fix lỗi Visual Studio 2022 not Support Target Net Framework 4.5.2
- [C#] Giới thiệu thư viện Sunny UI thiết kế giao diện trên Winform
- [DATABASE] Hướng dẫn thêm và cập nhật Extended Property Column trong Table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng Vertical Gridview để hiển thị thông tin sản phẩm
- [C#] Hướng dẫn sử dụng Json Schema để Validate chuỗi string có phải json
- [C#] Hướng dẫn sử dụng công cụ Clean Code trên Visual Studio
- [C#] Hướng dẫn Drag and Drop File vào RichTextBox
- [C#] Hướng dẫn tạo hiệu ứng Karaoke Text Effect Winform
- [C#] Sử dụng thư viện ZedGraph vẽ biểu đồ Line, Bar, Pie trên Winform
- [DATABASE] Hướng dẫn sort sắp xếp địa chỉ IP trên sqlserver sử dụng hàm PARSENAME
- [C#] Theo dõi sử kiện process Start hay Stop trên Winform
- [ASP.NET] Chia sẻ source code chụp hình sử dụng camera trên website
- [C#] Chạy ứng dụng trên Virtual Desktop (màn hình ảo) Winform
- [C#] Mã hóa và giải mã Data Protection API trên winform
- [C#] Hướng dẫn tạo Gradient Background trên Winform
- [DATABASE] Hướng dẫn convert Epoch to DateTime trong sqlserver
- [DATABASE] Hướng dẫn sử dụng STRING_AGG và CONCAT_WS trong sqlserver 2017
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!