Overkill Refactor
What's important?
- Splatting simplifies code a lot
- Changed paths to use
/
instead of\
to be more portable. Works on windows. - removed duplicates by renaming
$_
as$BaseName
,$OtherName
Pwsh 7
is only required forJoin-String -DoubleQuote
-- you can replace or poly fill itGet-Command '7z' -CommandType Application -Ea stop
ensures you get the7z.exe
even if7z
is an aliasJoin-Path
prevents errors, for example: Accidentally addinga/
to/b
to prevents an unexpected patha//b
- Creating
$zipArgs
from an array, like@()
simplifies your format strings
7z x "$env:TMP$($[0]).7z" -o"$env:TMP$($[0])"
I wasn't sure if the -o
is supposed to touch the double quote. I wrote it to output it that one.
$baseName | Join-String -DoubleQuote -op '-o'
#Requires -Version 7.0
# the only part that uses 7 is " | Join-String -DoubleQuote"
# but that's easy to polyfil
$SomeList | ForEach-Object {
$Name = $_[0]
$OtherName = $_[2]
$Uri = $_[1]
$BaseName = Join-Path $env:TMP $Name
$Dir = '' # wasn't in orignal
Write-Warning "Downloading, extracting & installing $Name..."
$invokeWebRequestSplat = @{
UseBasicParsing = $true
Uri = $Uri
OutFile = Join-Path $Env:Temp "${Name}.7z"
}
Invoke-WebRequest @invokeWebRequestSplat
while (-not(Test-Path $BaseName)) {
$null
}
# why emit null? maybe you wanted to exit the current function early
# meaning it skips this BaseName, continuing onto the next one
# because 'foreach-object' is a function
# ie: like 'continue' in a foreach block
if(-not (Test-Path $BaseName)) {
return
}
# make sure an alias or function doesn't override the native app
$bin7z = Get-Command '7z' -CommandType Application -Ea stop
# -DoubleQuote to ensure filepaths on the command line are being preserved
# original:
# 7z x "${baseName}.7z" -o"${baseName}"
$zipArgs = @(
'x'
"${BaseName}.7z" | Join-String -DoubleQuote
$baseName | Join-String -DoubleQuote -op '-o'
)
$zipArgs | Join-String -sep ' ' -op '7z args = '
& $bin7z @zipArgs
$moveItemSplat = @{
Force = $true
Path = Join-Path $env:TEMP $OtherName
Destination = Join-Path $DIR 'vapoursynth64/plugins'
}
Move-Item @moveItemSplat
Remove-Item "${BaseName}.7z", "${baseName}" -Force -Ea Ignore -Recurse
Join-Path $env:TEMP $OtherName | Join-String -DoubleQuote
Join-Path $Dir 'vapoursynth64/plugins' | Join-String -DoubleQuote
}
Original
@(
@( 'file1' 'url' 'location' )
@( 'file2' 'url' 'location' )
@( 'file3' 'url' 'location' )
) | ForEach-Object {
Write-Warning "Downloading, extracting & installing $($_[0])..."
Invoke-WebRequest -UseBasicParsing -Uri $_[1] -OutFile "$env:TMP\$($_[0]).7z"
while (-not(Test-Path "$env:TMP\$($_[0]).7z")){$null}
7z x "$env:TMP\$($_[0]).7z" -o"$env:TMP\$($_[0])"
Move-Item "$env:TEMP\$($_[2])" "$DIR\vapoursynth64\plugins" -Force
Remove-Item "$env:TMP\$($_[0]).7z","$env:TMP\$($_[0])" -Force -Ea Ignore -Recurse
}