Powershell: Install-dotNET4 function

Posted by marc dekeyser on Geeks with Blogs See other posts from Geeks with Blogs or by marc dekeyser
Published on Wed, 05 Dec 2012 10:52:22 GMT Indexed on 2012/12/05 17:05 UTC
Read the original article Hit count: 373

Filed under:
This function will download and install ,NET 4.0. It uses the Get-Framework-Versions function to determine if the installation is necessary or not. Internet Connectivity will be required as the script auto downloads the setup file (and sleeps for 360 seconds... I had a function in there to monitor for install completion at first, turns out the setup file spawns so many childprocesses the function just got confused and locked up -_-)

Alternatively you could drop the installation file in the folder specified on the $folderPath variable too. That will skip the download and use the file. This function easily adapts in to other versions f.e. I use it for Powershell 3 installs as well!

Function install-dotNet4 () {
    if(($InstalledDotNET -eq "4.0") -or ($InstalledDotNET -eq "4.0c")){
        write-host ".NET 4.0 Framework is already installed" -foregroundcolor Green
    } else{
    
        #set a var for the folder you are looking for
        $folderPath = 'C:\Temp'

        #Check if folder exists, if not, create it
        if (Test-Path $folderpath){
            Write-Host "The folder $folderPath exists." -ForeGroundColor Green
        } else{
            Write-Host "The folder $folderPath does not exist, creating..." -NoNewline -ForegroundColor Red
            New-Item $folderpath -type directory | Out-Null
            Write-Host " - done!" -ForegroundColor Green
        }

        # Check if file exists, if not, download it
        $file = $folderPath+"\dotNetFx40_Full_x86_x64.exe"
        if (Test-Path $file){
            write-host "The file $file exists." -ForeGroundColor Green
        } else {
            #Download Microsoft .Net 4.0 Framework
            Write-Host "Downloading Microsoft .Net 4.0 Framework..." -nonewline -ForeGroundColor DarkYellow
            $clnt = New-Object System.Net.WebClient
            $url = "http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe"
            $clnt.DownloadFile($url,$file)
            Write-Host " - done!" -ForegroundColor Green
        }
        #Install Microsoft .Net Framework
        Write-Host "Installing Microsoft .Net Framework..." -nonewline -ForegroundColor DarkYellow
        $dotNET4 = $folderPath+"\dotNetFx40_Full_x86_x64.exe /quiet /norestart"
        Invoke-Expression $dotNET4
        write-host " - done!" -ForegroundColor Green
        start-sleep -seconds 360
    }
}

© Geeks with Blogs or respective owner