Problem with foreach powershell

0

I have a small problem with a powershell script ... I'm learning how to program and I do not know how to solve it.

$descargas = "C:/Maqueta"

if(Test-Path -Path $descargas -PathType Container){
    Write-Host "El directorio $descargas ya esxiste" -ForegroundColor Yellow
}else{
    Write-Host "Creando directorio $descargas" -ForegroundColor Green
    New-Item -Path $descargas -ItemType directory
}

#Descargar

$lista = ("googlechromestandaloneenterprise64.msi","Winrar.exe")
$Uri =("https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B03FE9563-80F9-119F-DA3D-72FBBB94BC26%7D%26lang%3Den%26browser%3D4%26usagestats%3D0%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable/dl/chrome/install/googlechromestandaloneenterprise64.msi", 
       "https://www.winrar.es/descargas/103")

$destino = "$descargas"
#Error en los bucles

Foreach($var in $lista){     
   Foreach($var2 in $Uri){
    Invoke-WebRequest $var2 -OutFile $destino\$var

   }
}

At the time of downloading the indicated packages Google-Chrome and Winrar duplicates me the packages to the same in this case winrar. The download weight in the beginning is the correct one according to the google chrome package but for some reason winrar is downloaded again and overwrites the package.

This is an example of the problem.

And this is the same case, the packages are downloaded as different but they are the same.

Given my little experience in this world that is almost null I do not know what to do ...

    
asked by Andres Cabrera 19.06.2018 в 09:34
source

2 answers

0

As you have already been told in the comments, when you nest a foreach for the uris within a foreach for the names of the files, you are combining all the file names with all the uris. That is, in the end four calls are being made to Invoke-WebRequest equivalent to:

Invoke-WebRequest "https://dl.google.com..." -OutFile $destino\"googlechromestandaloneenterprise64.msi"

Invoke-WebRequest "https://www.winrar.es/descargas/103" -OutFile $destino\"googlechromestandaloneenterprise64.msi"

Invoke-WebRequest "https://dl.google.com..." -OutFile $destino\"Winrar.exe"

Invoke-WebRequest "https://www.winrar.es/descargas/103" -OutFile $destino\"Winrar.exe"

What I think you have to do is create an array in which each element has the information you need to perform a download, that is, url and local file where to download. It would look like this:

$ficherosADescargar=@();
$ficherosADescargar+= [PSCustomObject] @{
Uri="https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B03FE9563-80F9-119F-DA3D-72FBBB94BC26%7D%26lang%3Den%26browser%3D4%26usagestats%3D0%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable/dl/chrome/install/googlechromestandaloneenterprise64.msi"
Destino="googlechromestandaloneenterprise64.msi"}

$ficherosADescargar+= [PSCustomObject] @{
Uri="https://www.winrar.es/descargas/103"
Destino="Winrar.exe"}

Foreach($ficheroADescargar in $ficherosADescargar){
    Invoke-WebRequest $($ficheroADescargar.Uri) -OutFile (Join-Path $destino $ficheroADescargar.Destino)
}

As general recommendations:

  • Give descriptive names to the variables. var , var2 , lista and Uri are not good names
  • To compose routes, use Join- Path
  • Unless you are very sure that the script you are developing is use and throw , use Write-Host only when really necessary
  • answered by 19.06.2018 / 17:59
    source
    0
      

    This is the final execution of the Script

    < # Download and installation                     Ninja install     # >

    <#ROOT#>
    
    param([switch]$elevated)
    
    function Test-Admin {
       $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent()) 
       $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) 
    }
    
    if((Test-Admin) -eq $false){
        if($elevated){
            echo "Permisos no concedidos"
        }else{
            Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition)) 
        }
        exit
    }
    
    echo "Previlegios concedidos"
    
    #Establecemos la ruta de descarga
    $descargas = "C:\Dune"
    
    #Primero comprobamos si el directorio existe
    #De caso cotrario el directorio se va a crear según la rura establecida
    if(Test-Path -Path $descargas -PathType Container){
        Write-Host "El directorio $descargas ya esxiste" -ForegroundColor Yellow
    }else{
        Write-Host "Creando directorio $descargas" -ForegroundColor Green
        New-Item -Path $descargas -ItemType directory
    }
    
    #Ruta destino "Join-Path", compondremos la ruta
    $destino = "$descargas"
    
    #creamos un array en el que cada elemento tenga la información que necesitamos para realizar una descarga.
    #Uri y Destino( Ruta de la descarga )
    $ficherosADescargar=@();
    
    <#     Inicio elementos array     #>
    
    $ficherosADescargar+= [PSCustomObject] @{
    Uri="https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B03FE9563-80F9-119F-DA3D-72FBBB94BC26%7D%26lang%3Den%26browser%3D4%26usagestats%3D0%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable/dl/chrome/install/googlechromestandaloneenterprise64.msi"
    Destino="googlechromestandaloneenterprise64.msi"}
    
    
    $ficherosADescargar+= [PSCustomObject] @{
    Uri="http://rarlab.com/rar/winrar-x64-540.exe"
    Destino="Winrar.exe"}
    
    $ficherosADescargar+= [PSCustomObject] @{
    Uri="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=es-ES"
    Destino="Firefox.exe"
    }
    
    $ficherosADescargar+= [PSCustomObject] @{
    Uri="http://descargar.raanmavi.com/adobe-reader-dc-offline"
    Destino="AdobeReaderOfflineInstaller.exe"
    }
    
    $ficherosADescargar+= [PSCustomObject] @{
    Uri="https://fpdownload.macromedia.com/pub/labs/flashruntimes/flashplayer/install_flash_player.exe"
    Destino="FlashPlayerChrome.exe"
    }
    
    $ficherosADescargar+= [PSCustomObject] @{
    Uri="https://fpdownload.macromedia.com/pub/labs/flashruntimes/flashplayer/install_flash_player_ppapi.exe"
    Destino="FlashPlayerFirefox.exe"
    }
    
    
    <#     Fin elementos array     #>
    
    #Array de ejecutables .exe .msi
    $ejecutables=@()
    
    #Recorremos cada elemento del array
    Foreach($ficheroADescargar in $ficherosADescargar){
        #Descarga de ficheros
        Invoke-WebRequest $($ficheroADescargar.Uri) -OutFile (Join-Path $destino $ficheroADescargar.Destino)
        #Instalación de ficheros
        $ejecutables += Join-Path $destino $ficheroADescargar.Destino
    }
    
    
    ForEach($variable in $ejecutables){
       #Argumentos para la instalación
       $MSIargumentos=@(
                     "/i"
                     ('"{0}"' -f $variable)
                     "/passive"
                     "/L*V"
                     "C:\Dune\install.log"
                     )
    
        #Iniciamos la instalación de los programas
        if($variable -like '*.msi' ){
            Start-Process msiexec.exe -ArgumentList $MSIargumentos -Wait
        }else{
            if( $variable -like "*AdobeReaderOfflineInstaller.exe*"){
                Start-Process -FilePath  ('"{0}"' -f $variable) -ArgumentList "/sAll /rs /rps /msi /norestart /quiet EULA_ACCEPT=YES" -PassThru  -Wait
    
            }else{
                Start-Process -FilePath  ('"{0}"' -f $variable) -ArgumentList "/S" -PassThru  -Wait
            }
        }
    }
    
    remove-item C:\Dune\*.* -Exclude *.log
    
    Write-Host -Fore Green "La instalación ha terminado !!!!!!!"
    
        
    answered by 05.09.2018 в 17:52