- [DEVEXPRESS] Chia sẻ source code cách tạo biểu đồ sơ đồ tổ chức công ty Org Chart trên Winform C#
- [C#] Hướng dẫn tạo Auto Number trên Datagridview winform
- [DATABASE] Hướng dẫn tạo Procedure String Split in Mysql
- [C#] Thiết lập dấu (,) hay dấu (.) ở định dạng số đúng với định dạng số Việt Nam
- [C#] Chia sẻ source code Game Spin Lucky Wheel
- [C#] Hướng dẫn Encode and Decode HTML
- Hướng dẫn tạo tài khoản Chat Open AI GPT tại Việt Nam
- [C#] Hướng dẫn thay đổi giao diện ứng dụng Winform theo giao diện của Windows
- [VB.NET] Hiệu ứng Acrylic, Mica, Tabbed Blur Effect trên Winform
- [DEVEXPRESS] Hướng dẫn sử dụng HTML Template trên Combobox Edit
- [C#] Chia sẻ source code Orange Rain in Winform
- [DEVEXPRESS] Hướng dẫn sử dụng HTML Template trên XtraMessageBox Winform Devexpress 22.2.3
- [DEVEXPRESS] Hướng dẫn sử dụng HTML and CSS Code Viewer trên Winform
- [C#] Number Effect Counter up and down in winform
- [C#] Hướng dẫn Supend and Resume Process ID in Winform
- [C#] Hiển thị line number trên Richtextbox Winform
- [C#] Fake Blue Screen BSOD in winform
- [C#] Chia sẽ code demo sử dụng Async Parallel Foreach and For in Winform
- [C#] Sử dụng ActionBlock run X task at time winform
- [C#] Hướng dẫn sử dụng Property Grid để lưu và tải lại thông tin cấu hình user trên winform
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!