AegisShimon
AegisShimon

Reputation: 25

Can anyone help me create a progress bar in powershell while the script is running?

I've already tested Write-Progress, and when I put it multiple times along with a "Start-Sleep -Milliseconds 250" it seems to work perfectly, but when I try to implement it in my script, where I put the percentage in each script step, it doesn't work . Only the first bar appears but it doesn't evolve to 100%. I've been trying to get this to work for a few days now (because in the end I use ps2exe so I'll have visible feedback on what's being done behind the scenes) and I'm not succeeding.

Here is my code:

# Here is defined the variable that stores the hostname of the user through a pipeline to a Visual Basic window, note, if you put any information after the quotes after the "Audit Report" it will become a suggestion message
Add-Type -AssemblyName Microsoft.VisualBasic
$ComputerHost = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the Hostname of the machine", "Audit Report")
If ($ComputerHost -eq "")
{
    break
}

Write-Progress -Activity "Starting data capture" -PercentComplete 10
Start-Sleep -Milliseconds 250

#Performing validation if the equipment is on the network, if so, the script will continue, otherwise, it will be canceled informing that the equipment has insufficient requirements for the operation.
$ProgressPreference = 'SilentlyContinue'
 $TestComputerHost = Test-Connection $ComputerHost -Count 1 -InformationAction Continue -WarningAction SilentlyContinue
If (($TestComputerHost -ne "") -or ($TestComputerHost -ne $null))
{}
Else {
    [Microsoft.VisualBasic.Interaction]::MsgBox("ERROR: Computer $ComputerHost not responding on network.", "OKOnly,SystemModal,Critical", "Error")
    break
}

Write-Progress -Activity "Starting data capture" -PercentComplete 15
Start-Sleep -Milliseconds 250

$TestComputerHost = Test-NetConnection $ComputerHost -Port 5985 -InformationLevel Quiet -WarningAction SilentlyContinue
If ($TestComputerHost -ne "False"){
    [Microsoft.VisualBasic.Interaction]::MsgBox("WARNING: Computer $ComputerHost is responding on the network but has not identified remote management enabled, some data may be incomplete!", "OKOnly,SystemModal,Exclamation", "Warning")
}


#Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine
Function Get-WUCchassisType {

    [CmdletBinding()]
    stop (
    )
    Set-StrictMode -Version 'Latest'
    [int[]]$chassisType = try {
    $ErrorActionPreference = "Stop";
    Get-CimInstance Win32_SystemEnclosure -ComputerName $ComputerHost | Select-Object -ExpandProperty ChassisTypes;
    } catch {
    Write-Warning "WARNING: It was not possible to get the user logged into the remote equipment!";
    } finally {
    $ErrorActionPreference = "Continue";
    }
    switch($chassisType) {
        { $_ -in 3, 4, 5, 6, 7, 15, 16 } {
            return 'Desktop'
        }
        { $_ -in 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 } {
            return 'Notebook'
        }
        { $_ -in 30 } {
            return 'Tablet'
        }
        { $_ -in 17, 23 } {
            return 'Server'
        }
        Default {
        }
    }
}


#Function to get the last logged in user
Function Get-LastUser {
Get-WmiObject Win32_LoggedOnUser -ComputerName $ComputerHost |
    Select Antecedent -Unique |
    % {
        $domain = $_.Antecedent.Split('"')[1]
        if($domain -eq "DOMAIN") {
            "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3]
        }
    } | Select-Object -First 1
    }


Write-Progress -Activity "Starting data capture" -PercentComplete 20
Start-Sleep -Milliseconds 250

#HTML Report - Report generated in...
$output+="<tr><td><b>Report generated in</b> " + (Get-Date -UFormat "%d/%m/%Y %R:%S") + "</td> </tr>`n"

Write-Progress -Activity "Starting data capture" -PercentComplete 25
Start-Sleep -Milliseconds 250

#HTML Report - Audit Report
$output+="<h1>Audit Report</h1><br>"

Write-Progress -Activity "Starting data capture" -PercentComplete 30
Start-Sleep -Milliseconds 250

#HTML Report - Computer
$output+="<table><tr><td><h1><b>Computer:`n`n</b>"+$ComputerHost+"</h1></td></tr>`n"

Write-Progress -Activity "Starting data capture" -PercentComplete 35
Start-Sleep -Milliseconds 250

#HTML Report - Currently Connected User:
#GetRemoteUser uses an invoke command expression to retrieve the information of the user who is logged into the remote machine
#$AutoEnableWinRM = Invoke-Command -ComputerName $ComputerHost -ScriptBlock { winrm quickconfig -quiet } | Out-Null
$output+="<table><tr><td><table><tr><td><tr><td><b>Currently logged in user:`n`n</b>"+((Get-LastUser ).Split('\')[1])+"</td></tr>"

Write-Progress -Activity "Starting data capture" -PercentComplete 40
Start-Sleep -Milliseconds 250

#HTML Report - Last Boot Time
$output+="<table><tr><td><table><tr><b>Last Boot Time:`n`n</b>"+(gwmi win32_operatingsystem -ComputerName $ComputerHost | Select-Object @{ Label="LastBootTime"; Expression={$_.ConvertToDateTime($_.LastBootUpTime)}} | Select -ExpandProperty LastBootTime).tostring("dd/MM/yyyy hh:mm:ss") +"</td>< /tr>"

# Just whitespace to make the HTML more readable and organized
$output+="<td><tr></td></tr><br>"
$output+="<td><tr></td></tr>"
$output+="<td><tr></td></tr><br>"
$output+="<td><tr></td></tr>"

Write-Progress -Activity "Starting data capture" -PercentComplete 45
Start-Sleep -Milliseconds 250

#HTML Report - RAM Memory
$output+="<table><tr><b>RAM:`n`n</b>" +(gwmi -class Win32_PhysicalMemory -ComputerName $ComputerHost | Measure-Object -Property capacity -Sum | % {[Math] ::Round(($_.sum / 1GB),2)})+"GB`n"

# Just whitespace to make the HTML more readable and organized
$output+="<td><tr></td></tr><br>"
$output+="<td><tr></td></tr>"

Write-Progress -Activity "Starting data capture" -PercentComplete 80
Start-Sleep -Milliseconds 250

#HTML Report - Serial Number
$output+="<table><tr><b>Serial Number:</b>`n`n"+(gwmi win32_bios -ComputerName $ComputerHost -property SerialNumber |select -exp SerialNumber) +"</td>< /tr>"

# Just whitespace to make the HTML more readable and organized
$output+="<td><tr></td></tr><br>"
$output+="<td></td></tr>"

Write-Progress -Activity "Starting data capture" -PercentComplete 85
Start-Sleep -Milliseconds 250

#HTML Report - Manufacturer
$output+="<table><tr><b>Manufacturer:</b>`n`n"+(gwmi win32_ComputerSystemProduct -ComputerName $ComputerHost -property Vendor |select -exp Vendor) +"</td></tr >"

# Just whitespace to make the HTML more readable and organized
$output+="<td><tr></td></tr><br>"
$output+="<td></td></tr>"

Write-Progress -Activity "Starting data capture" -PercentComplete 90
Start-Sleep -Milliseconds 250
Start-Sleep -Milliseconds 250

#HTML Report - Template
$output+="<table><tr><b>Model:</b>`n`n"+(gwmi win32_ComputerSystemProduct -ComputerName $ComputerHost -property Name |select -exp Name) +"</td></tr >"

Write-Progress -Activity "Starting data capture" -PercentComplete 95
Start-Sleep -Milliseconds 250

# Output to export the report file
Out-File -FilePath ".\$ComputerHost-$((Get-Date).ToString("dd-MM-yyyy-HH-mm"))_Report.html" -Encoding default -InputObject $output

# Makes a copy of the report file to a temporary folder, where it will be executed as soon as the script finishes
Copy-Item -Path ".\$ComputerHost-$((Get-Date).ToString("dd-MM-yyyy-HH-mm"))_Report.html" -Destination "$env:TEMP\$ComputerHost.html " -Force

Write-Progress -Activity "Starting data capture" -Completed
Start-Sleep -Milliseconds 250

#Performs a conditional structure validation to define which browser is the default on the local user's computer.
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser', $env:COMPUTERNAME)
$RegKey= $Reg.OpenSubKey("Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice")
$BrowserProgId = $RegKey.GetValue("ProgId")
$BrowserProgId = $BrowserProgId.Split('-')[0]

if ($BrowserProgId -eq "ChromeHTML") {
$DefaultBrowser="chrome.exe"}

elseif ($BrowserProgId -eq "MSEDgeHTM") {
$DefaultBrowser = "msedge.exe"}

elseif ($BrowserProgId -eq "FirefoxURL") {
$DefaultBrowser = "firefox.exe"}

[Microsoft.VisualBasic.Interaction]::MsgBox("Report generated successfully!", "OKOnly,SystemModal,Information", "Success") | Out-Null

#Initializes the report file that was previously copied to the temp folder invoking the user-defined default browser.
cmd.exe /c "start $DefaultBrowser "%temp%\$ComputerHost.html""

Start-Sleep 10
Remove-Item -Path "$env:TEMP\$ComputerHost.html" -Force | Out-Null

# Clear the main variable, useful if this is running in a powershell_ise
Clear-Variable output```

Upvotes: 0

Views: 917

Answers (0)

Related Questions