Powershell: Get VM Properties - powershell

I Created a VM and I want to export its properties in a CSV file.
what I tried does not give me the IPAddress, SwitchName, Macaddress.
$Data = #();
$VMs = Get-VM $VMName;
foreach($VM in $VMs){
$VMCustom = New-Object System.Object;
$VMCustom | Add-Member -Type NoteProperty -Name VMName -Value $VM.VMName;
# Get-VMNetworkAdapter -VMName $VMName | Select -expand IPAddresses
$VMCustom | Add-Member -Type NoteProperty -Name IPAddress -Value $VM.guest.IPAddresses;
$VMCustom | Add-Member -Type NoteProperty -Name SwitchName -Value $VM.MacAddress;
$VMCustom | Add-Member -Type NoteProperty -Name Status -Value $VM.State;
$VMCustom | Add-Member -Type NoteProperty -Name Generation -Value $VM.Generation;
$VMCustom | Add-Member -Type NoteProperty -Name SwitchName -Value $VM.SwitchName;
$Data += $VMCustom;
}
$Data | Export-CSV "C:\VM.csv" -Delimiter ";";
Question: Is the Ipaddress, the IPaddress of the VM or the IPaddress of the Hyper-V?
That would be great if someone could help me out.

Try this:
$Data = #()
$VMs = "Server-001","Server-002","Server-003"
foreach($VM in $VMs)
{
$VMInfo = Get-VM -Name $VM
$VMNetwork = $VMInfo | Get-VMNetworkAdapter
$VMCustom = New-Object System.Object
$VMCustom | Add-Member -Type NoteProperty -Name VMName -Value $VMInfo.VMName
$VMCustom | Add-Member -Type NoteProperty -Name Status -Value $VMInfo.Status
$VMCustom | Add-Member -Type NoteProperty -Name Generation -Value $VMInfo.Generation
$VMCustom | Add-Member -Type NoteProperty -Name IPAddress -Value $VMNetwork.IPAddresses[0]
$VMCustom | Add-Member -Type NoteProperty -Name MacAddress -Value $VMNetwork.MacAddress
$VMCustom | Add-Member -Type NoteProperty -Name SwitchName -Value $VMNetwork.SwitchName
$Data += $VMCustom
}
$Data | Export-CSV "C:\VM.csv" -Delimiter ";" -NoTypeInformation

Related

Powershell object doesn't add member

For some reason when I wrote this Powershell object, the last member does not get displayed in my result:
$resultObject = New-Object -TypeName psobject
$resultObject | Add-Member -MemberType NoteProperty -Name Date -Value $date
$resultObject | Add-Member -MemberType NoteProperty -Name TotalPCs -Value $ad
$resultObject | Add-Member -MemberType NoteProperty -Name UnmanagedTotal -Value $total
$resultObject | Add-Member -MemberType NoteProperty -Name TotalEMEA -Value $adEMEA
$resultObject | Add-Member -MemberType NoteProperty -Name UnmanagedEMEA -Value $totalEMEA
$resultObject | Add-Member -MemberType NoteProperty -Name TotalAFRICA -Value $adAFRICA
$resultObject | Add-Member -MemberType NoteProperty -Name UnmanagedAFRICA -Value $totalAFRICA
$resultObject | Add-Member -MemberType NoteProperty -Name TotalAMERICAS -Value $adAMERICAS
$resultObject | Add-Member -MemberType NoteProperty -Name UnmanagedAMERICAS -Value $totalAMERICAS
$resultObject | Add-Member -MemberType NoteProperty -Name TotalAPAC -Value $adAPAC
$resultObject | Add-Member -MemberType NoteProperty -Name UnmanagedAPAC -Value $totalAPAC
$resultObject | ft -AutoSize | out-file -FilePath "C:\BAC\WSUSScripts\KPI\ManagedComputers.txt" -Append
I have no clue why since every info is retrieved the same way and for the other member it all works. The last member just falls off.

If Else Loop not working in Powershell Inventory Script

Note – I am not a coding expert so please be gentle 😊 Any assistance/guidance much appreciated
Issue is that my pieced together Powershell script is not working as correctly. I am guessing it will take a coding guru two seconds to help resolve.
The basics of the script is that it performs a basic audit of a list of servers from a text file and outputs the results to a csv. For each server it will test WMI connection and if successful will collect columns of data i.e Name, IP Address, Uptime etc. If WMI connection fails then it should just log a few columns of data i.e. WMI Result, Ping Result etc All results should be piped to the same single output csv
The script works perfectly if the first server in the list’s WMI connection succeeds. All 16 x columns of csv output file are populated for every server in list.
WorkingExample
If the first server in the list’s WMI connection fails then the output fails. Only 4 x columns of csv output file are populated for every server in list.
FailingExample
Hopefully the screenshots of the output csv's help
Powershell Code below
<#
.DESCRIPTION - Auditing Script - Construction Phase !!!
- Create folder called 'Audit' under C:\Temp
- Create text file called 'Servers.txt' and place in newly created C:\Temp\Audit folder
- Servers.txt should contain a list of server names you wish to audit\target
.Author MCD
#>
########## Output Folder ##########
$outputFolderName = 'Audit ' + $(Get-Date -f dd-MM-yyyy)
$outputpath = "C:\temp\Audit\$outputFolderName"
If(!(test-path $outputpath))
{
New-Item -ItemType Directory -Force -Path $outputpath | out-null
}
########## Prompt 1 ##########
Add-Type -AssemblyName Microsoft.VisualBasic
$ClientName = [Microsoft.VisualBasic.Interaction]::InputBox('Please enter Client\Customer name i.e. Contoso Ltd', 'User')
Start-Sleep -s 2
#Manual Input File Location
$computers = Get-Content -path c:\temp\audit\Servers.txt
########## Create an Empty Array ##########
$report = #()
########## Main Start ##########
Foreach ($Computer in $Computers)
{
########## WMI/Ping Test ##########
$wmi = gwmi win32_bios -ComputerName $computer -ErrorAction SilentlyContinue
$Ping = Test-Connection -ComputerName $computer -Quiet -count 2
########## Main If Else Loop ##########
if ($wmi)
{
$WMIResult = 'Server IS Contactable'
########## HW/Serial No/Bios ##########
$Bios = Get-WmiObject -Class win32_bios -ComputerName $Computer
$systemBios = $Bios.serialnumber
$Hardware = Get-WmiObject -Class Win32_computerSystem -ComputerName $Computer
########## OS Version/Last Reboot ##########
$OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
$lastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
$uptimeDays = ((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).Days
########## Network Info ##########
$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $Computer | Where-Object {$_.IPEnabled}
$IPAddress = ($Networks.IpAddress | where {$_ -notmatch ":"}) -join "`n"
$MACAddress = ($Networks.MACAddress) -join "`n"
$IpSubnet = ($Networks.IpSubnet | ? { $_ -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' }) -join "`n"
$DefaultGateway = ($Networks.DefaultIPGateway) -join "`n"
########## LastLogon/Created ##########
$LastLogonDate = Get-ADComputer $computer -Properties * | select -ExpandProperty LastLogonDate
$Created = Get-ADComputer $computer -Properties * | select -ExpandProperty Created
########## OUTPUT ##########
$tempreport = New-Object -TypeName PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Hardware.Manufacturer
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $Hardware.Model
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $OS.Caption
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $IPAddress
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $DefaultGateway
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $MACAddress
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $IpSubnet
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $lastboot
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $uptimeDays
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $LastLogonDate
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $Created
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $systemBios
$report += $tempreport
} else {
$WMIResult = 'Server NOT Contactable'
$tempreport = New-Object PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$report += $tempreport
}
}
########## EXPORT TO CSV ##########
$CSVFileName = $ClientName + ' Server Inventory ' + $(Get-Date -f dd-MM-yyyy) + '.csv'
$report | Export-Csv "$outputpath\$CSVFileName" -NoTypeInformation
<#
.END
#>
The issue is that the two objects you are creating don't contain the same properties. Arrays will report the information based on the properties in the first object. So if the first object fails, then all the others will report back the same four properties when the array is output.
My suggestion for dealing with this in the most simple way is to add the additional properties to the failing object, setting the values as $null. This should see that your CSV receives all the properties as intended.
<#
.DESCRIPTION - Auditing Script - Construction Phase !!!
- Create folder called 'Audit' under C:\Temp
- Create text file called 'Servers.txt' and place in newly created C:\Temp\Audit folder
- Servers.txt should contain a list of server names you wish to audit\target
.Author MCD
#>
########## Output Folder ##########
$outputFolderName = 'Audit ' + $(Get-Date -f dd-MM-yyyy)
$outputpath = "C:\temp\Audit\$outputFolderName"
If(!(test-path $outputpath)) {
New-Item -ItemType Directory -Force -Path $outputpath | out-null
}
########## Prompt 1 ##########
Add-Type -AssemblyName Microsoft.VisualBasic
$ClientName = [Microsoft.VisualBasic.Interaction]::InputBox('Please enter Client\Customer name i.e. Contoso Ltd', 'User')
Start-Sleep -s 2
#Manual Input File Location
$computers = Get-Content -path c:\temp\audit\Servers.txt
########## Create an Empty Array ##########
$report = #()
########## Main Start ##########
Foreach ($Computer in $Computers) {
########## WMI/Ping Test ##########
$wmi = gwmi win32_bios -ComputerName $computer -ErrorAction SilentlyContinue
$Ping = Test-Connection -ComputerName $computer -Quiet -count 2
########## Main If Else Loop ##########
if ($wmi) {
$WMIResult = 'Server IS Contactable'
########## HW/Serial No/Bios ##########
$Bios = Get-WmiObject -Class win32_bios -ComputerName $Computer
$systemBios = $Bios.serialnumber
$Hardware = Get-WmiObject -Class Win32_computerSystem -ComputerName $Computer
########## OS Version/Last Reboot ##########
$OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
$lastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
$uptimeDays = ((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).Days
########## Network Info ##########
$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $Computer | Where-Object {$_.IPEnabled}
$IPAddress = ($Networks.IpAddress | where {$_ -notmatch ":"}) -join "`n"
$MACAddress = ($Networks.MACAddress) -join "`n"
$IpSubnet = ($Networks.IpSubnet | ? { $_ -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' }) -join "`n"
$DefaultGateway = ($Networks.DefaultIPGateway) -join "`n"
########## LastLogon/Created ##########
$LastLogonDate = Get-ADComputer $computer -Properties * | select -ExpandProperty LastLogonDate
$Created = Get-ADComputer $computer -Properties * | select -ExpandProperty Created
########## OUTPUT ##########
$tempreport = New-Object -TypeName PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Hardware.Manufacturer
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $Hardware.Model
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $OS.Caption
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $IPAddress
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $DefaultGateway
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $MACAddress
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $IpSubnet
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $lastboot
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $uptimeDays
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $LastLogonDate
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $Created
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $systemBios
$report += $tempreport
}
else {
$WMIResult = 'Server NOT Contactable'
$tempreport = New-Object PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $null
$report += $tempreport
}
}
########## EXPORT TO CSV ##########
$CSVFileName = $ClientName + ' Server Inventory ' + $(Get-Date -f dd-MM-yyyy) + '.csv'
$report | Export-Csv "$outputpath\$CSVFileName" -NoTypeInformation

Adding data from a second Invoke-WebRequest import into an existing array

I am fairly new to powershell and am having a problem with my script adding data from a second Invoke-WebRequest into an existing array $arr1.
The second import into variable $annotations works fine. I then need to match where $vm.Name = $annotations.Name in order for final ForEach($vm in $vms) to work and pull in the annotations data as well but am stuck.
My code is as follows. Please help
$StorageSystemName = "storageName"
$StoragePoolName = "storagepool"
$ReportName = "~\Reports\ServerList_$((Get-Date).ToString('yyyy-MM-dd')).xlsx"
Invoke-WebRequest -Uri http://srv1/location/Report_volume_storage.csv -OutFile .\Report_volume_storage.csv
$luns = Import-Csv .\Report_volume_storage.csv -Delimiter ";" |
Where-Object {$_.'Storage System name' -eq $StorageSystemName -and $_.'Storage Pool Name' -eq $StoragePoolName -and $_.'Volume Name'} |
Sort-Object "Storage Pool Name", "Volume Name"
Invoke-WebRequest -Uri http://srv2/addmdata/addmdata.csv -OutFile .\addmdata.csv
$annotations = Import-Csv .\addmdata.csv -Delimiter "," |
Select #{n='Name';e={$_.name.Split('.')[0]}}, * -Exclude Name,
#{n="Annotationserverdescription";e={$_.'Server Description'}},
#{n="Annotationapowner";e={$_.'Annotationapowner (Annotationappowner)'}},
#{n="Annotationclient";e={$_.'Client'}}
Sort-Object Name
$arr1 = #()
ForEach($lun in $luns)
{
$dsnaa = $lun.'LUN UID'
$dsnaa = "*$dsnaa*"
$datastore = Get-Datastore |
Where {($_.ExtensionData.Info.Vmfs.Extent).DiskName -like $dsnaa}
$VMs = #()
$datastore | ForEach-Object {
$dstore = $_.name
$VMs += get-VM -datastore $dstore | Where {$_.PowerState -eq "PoweredOn"} | Select #{n="Name";e={$_.name}}, #{n="PowerState";e={$_.PowerState}}, #{n="Datastore_Name";e={$dstore}}
}
ForEach($vm in $vms)
{
$data = New-Object System.Object
$data | Add-Member -MemberType NoteProperty -Name "Name" -Value $vm.Name
$data | Add-Member -MemberType NoteProperty -Name "PowerState" -Value $vm.PowerState
$data | Add-Member -MemberType NoteProperty -Name "Annotationserverdescription" -Value $annotation.'Server Description'
$data | Add-Member -MemberType NoteProperty -Name "Annotationapowner" -Value $annotation.'Annotationapowner (Annotationappowner)'
$data | Add-Member -MemberType NoteProperty -Name "Annotationclient" -Value $annotation.Client
$data | Add-Member -MemberType NoteProperty -Name "Volume Name" -Value $lun.'Volume Name'
$data | Add-Member -MemberType NoteProperty -Name "LUN UID" -Value $lun.'LUN UID'
$data | Add-Member -MemberType NoteProperty -Name "Capacity (GiB)" -Value $lun.'Capacity (GiB)'
$data | Add-Member -MemberType NoteProperty -Name "Storage Pool Name" -Value $lun.'Storage Pool Name'
$data | Add-Member -MemberType NoteProperty -Name "Storage System name" -Value $lun.'Storage System name'
$data | Add-Member -MemberType NoteProperty -Name "Storage Tier" -Value $lun.'Storage Tier'
$arr1 += $data
}
}
$arr1 | Export-Excel $ReportName
You could do something like the following:
$StorageSystemName = "storageName"
$StoragePoolName = "storagepool"
$ReportName = "~\Reports\ServerList_$((Get-Date).ToString('yyyy-MM-dd')).xlsx"
Invoke-WebRequest -Uri http://srv1/location/Report_volume_storage.csv -OutFile .\Report_volume_storage.csv
$luns = Import-Csv .\Report_volume_storage.csv -Delimiter ";" |
Where-Object {$_.'Storage System name' -eq $StorageSystemName -and $_.'Storage Pool Name' -eq $StoragePoolName -and $_.'Volume Name'} |
Sort-Object "Storage Pool Name", "Volume Name"
Invoke-WebRequest -Uri http://srv2/addmdata/addmdata.csv -OutFile .\addmdata.csv
$annotations = Import-Csv .\addmdata.csv -Delimiter "," |
Select #{n='Name';e={$_.name.Split('.')[0]}}, * -Exclude Name,
#{n="Annotationserverdescription";e={$_.'Server Description'}},
#{n="Annotationapowner";e={$_.'Annotationapowner (Annotationappowner)'}},
#{n="Annotationclient";e={$_.'Client'}}
Sort-Object Name
$arr1 = #()
ForEach($lun in $luns)
{
$dsnaa = $lun.'LUN UID'
$dsnaa = "*$dsnaa*"
$datastore = Get-Datastore |
Where {($_.ExtensionData.Info.Vmfs.Extent).DiskName -like $dsnaa}
$VMs = #()
$datastore | ForEach-Object {
$dstore = $_.name
$VMs += get-VM -datastore $dstore | Where {$_.PowerState -eq "PoweredOn"} | Select #{n="Name";e={$_.name}}, #{n="PowerState";e={$_.PowerState}}, #{n="Datastore_Name";e={$dstore}}
}
ForEach($vm in $vms)
{
$ActiveAnnotation = $null
$ActiveAnnotation = $annotations | where-object {$_.name -eq $vm.name}
$data = New-Object System.Object
$data | Add-Member -MemberType NoteProperty -Name "Name" -Value $vm.Name
$data | Add-Member -MemberType NoteProperty -Name "PowerState" -Value $vm.PowerState
$data | Add-Member -MemberType NoteProperty -Name "Annotationserverdescription" -Value $ActiveAnnotation.'Server Description'
$data | Add-Member -MemberType NoteProperty -Name "Annotationapowner" -Value $ActiveAnnotation.'Annotationapowner (Annotationappowner)'
$data | Add-Member -MemberType NoteProperty -Name "Annotationclient" -Value $ActiveAnnotation.Client
$data | Add-Member -MemberType NoteProperty -Name "Volume Name" -Value $lun.'Volume Name'
$data | Add-Member -MemberType NoteProperty -Name "LUN UID" -Value $lun.'LUN UID'
$data | Add-Member -MemberType NoteProperty -Name "Capacity (GiB)" -Value $lun.'Capacity (GiB)'
$data | Add-Member -MemberType NoteProperty -Name "Storage Pool Name" -Value $lun.'Storage Pool Name'
$data | Add-Member -MemberType NoteProperty -Name "Storage System name" -Value $lun.'Storage System name'
$data | Add-Member -MemberType NoteProperty -Name "Storage Tier" -Value $lun.'Storage Tier'
$arr1 += $data
}
}
$arr1 | Export-Excel $ReportName
I added the $ActiveAnnotation variable inside of your VMs loop to find the annotation match each time through the loop.

OpenVAS Scan Data Manipulation

enter image description hereI'm attempting to write a Powershell script that takes an OpenVAS .csv file and outputs it in a format that I can upload into Jira. I've written one working script that takes each scan item and creates it's own entry, which definitely has some room for improvement. I've been attempting to create a script that takes all the hosts that has the vulnerability "TCP Timestamps" (as an example) and create only one csv entry.
Starting Input (heavily sanitized):
enter image description here
First working script (makes an individual ticket for each item):
# Function for file picker
Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
$scanImport = #()
$csvContents = #()
$inputFile = Get-FileName "C:\temp"
$scanImport = Import-CSV $inputFile
# Removes the Information vulnerabilities
$scanImport = #($scanImport | Where-Object {$_."Risk Level" -ne "Info"})
$scanImport | Sort Vulnerability | ForEach {
$row = New-Object System.Object
$row | Add-Member -MemberType NoteProperty -Name "Hostname" -Value $_.Hostname
$row | Add-Member -MemberType NoteProperty -Name "IP Address" -Value $_."Host IP"
$row | Add-Member -MemberType NoteProperty -Name "Vulnerability Base Rating" -Value $_."Risk Level"
$row | Add-Member -MemberType NoteProperty -Name "Detection Method" -Value "OpenVAS"
$row | Add-Member -MemberType NoteProperty -Name "Vulnerability Name" -Value $_.Vulnerability.Split("`n")[0]
$row | Add-Member -MemberType NoteProperty -Name "Summary" -Value ($_.Hostname + " - " + $_.Vulnerability.Split("`n")[0])
$row | Add-Member -MemberType NoteProperty -Name "References" -Value ("Observation:" + " " + $_.Observation + "`n`n" + "Remediation:" + " " + $_.Remedation + "`n`n" + "Consequences:" + " " + $_.Consequences + "`n`n" + "Test Output:" + " " + $_."Test Output")
$row | Add-Member -MemberType NoteProperty -Name "Assigned To" -Value user1
$row | Add-Member -MemberType NoteProperty -Name "System Owner" -Value user2
$row | Add-Member -MemberType NoteProperty -Name "Users Affected" -Value "Needs to be entered"
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals" -Value user3
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals1" -Value user4
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals2" -Value user5
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals3" -Value user6
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals4" -Value user7
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals5" -Value user8
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals6" -Value user9
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals7" -Value user10
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals8" -Value user11
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals9" -Value user12
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals10" -Value user13
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals11" -Value user14
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals12" -Value user15
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals13" -Value user16
$csvContents += $row
}
$csvContents | Export-CSV -Path "\Users\$env:USERNAME\Desktop\OpenVAS_to_Jira.csv" -NoTypeInformation
First Script Output (hostnames and vuln names redacted. I used an old vuln scan but out of precaution):
script output
Second Script Attempt (with the grouping functionality):
# Function for file picker
Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
$scanImport = #()
$csvContents = #()
$hostnames = #()
$hostIPs = #()
$vulnList = #()
$counter = 0
$inputFile = Get-FileName "C:\temp"
$scanImport = Import-CSV $inputFile
# Removes the Information vulnerabilities
$scanImport = #($scanImport | Where-Object {$_."Risk Level" -ne "Info"} | Sort Vulnerability)
$scanImport | Sort Vulnerability |
ForEach {
$vulnName = $_.Vulnerability.Split("`n")[0]
$row = New-Object System.Object
if ($scanImport[$counter].Vulnerability -eq $scanImport[($counter+1)].Vulnerability) {
$hostnames += $_.Hostname
$hostIPs += $_."Host IP"
}
else {
if ($hostnames -eq $null) {
$row | Add-Member -MemberType NoteProperty -Name "Summary" -Value ($_.Hostname + " - " + $_.Vulnerability.Split("`n")[0])
$row | Add-Member -MemberType NoteProperty -Name "Hostname" -Value $_.Hostname
$row | Add-Member -MemberType NoteProperty -Name "IP Address" -Value $_."Host IP"
}
else
{
$row | Add-Member -MemberType NoteProperty -Name "Summary" -Value ("Multiple Systems" + " - " + $_.Vulnerability.Split("`n")[0])
$row | Add-Member -MemberType NoteProperty -Name "Hostname" -Value $hostnames
$row | Add-Member -MemberType NoteProperty -Name "IP Address" -Value $hostIPs
$hostnames = #()
$hostIPs = #()
}
$row | Add-Member -MemberType NoteProperty -Name "Vulnerability Base Rating" -Value $_."Risk Level"
$row | Add-Member -MemberType NoteProperty -Name "Detection Method" -Value "OpenVAS"
$row | Add-Member -MemberType NoteProperty -Name "Vulnerability Name" -Value $_.Vulnerability.Split("`n")[0]
$row | Add-Member -MemberType NoteProperty -Name "References" -Value ("Observation:" + " " + $_.Observation + "`n`n" + "Remediation:" + " " + $_.Remedation + "`n`n" + "Consequences:" + " " + $_.Consequences + "`n`n" + "Test Output:" + " " + $_."Test Output")
$row | Add-Member -MemberType NoteProperty -Name "Assigned To" -Value user1
$row | Add-Member -MemberType NoteProperty -Name "System Owner" -Value user2
$row | Add-Member -MemberType NoteProperty -Name "Users Affected" -Value "Needs to be entered"
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals" -Value user3
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals1" -Value user4
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals2" -Value user5
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals3" -Value user6
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals4" -Value user7
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals5" -Value user8
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals6" -Value user9
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals7" -Value user10
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals8" -Value user11
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals9" -Value user12
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals10" -Value user13
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals11" -Value user14
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals12" -Value user15
$row | Add-Member -MemberType NoteProperty -Name "DS: Approvals13" -Value user16
$csvContents += $row
$counter += 1
}
}
$csvContents | Export-CSV -Path "\Users\$env:USERNAME\Desktop\OpenVAS_to_Jira.csv" -NoTypeInformation
Essentially, I want the output to look something like this (excel mock up):
desired output
I know there's a high chance I made quite a bit of errors or didn't code something the right way, but I'd appreciate any feedback and help. Thanks in advance!
$input = Import-Csv "C:\input.csv"
$Vulnerabilities = $input | Group-Object -Property Vulnerability -AsHashTable -AsString
foreach ($Vulnerability in ($Vulnerabilities.Keys | Sort-Object)) {
$row = [PSCustomObject]#{
"Hostname" = (($Vulnerabilities.$Vulnerability.HostName) -join ', ')
"IP Address" = (($Vulnerabilities.$Vulnerability."Host IP") -join ',')
"Vulnerability Base Rating" = ($Vulnerabilities.$Vulnerability)[0]."Risk Level"
"Detection Method" = "OpenVAS"
"Vulnerability Name" = $Vulnerability
}
Export-Csv -InputObject $row -Path "C:\output.csv" -Append -NoTypeInformation
}

esxi detailed Information

I want to get all the information from ESXi. I extracted the information in different CSV files, but once I want to merge them, it does not show all. But I would rather to create foreach to gather same information.
Add-PsSnapin VMware.VimAutomation.Core -ErrorAction "SilentlyContinue"
Import-Module ‚C:\Program Files\Microsoft Virtual Machine Converter\MvmcCmdlet.psd1‘
$datetime = Get-Date -Format "ddMMyyyy";
# Configuration Block
$User =
$Password =
$ESXiServer = "172.17.1.171"
# Connect to ESXi
$PWD = ConvertTo-SecureString -AsPlainText -Force -String $Password;
$SourceCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User,$PWD;
$sourceConnection = New-MvmcSourceConnection -Server $ESXiServer -SourceCredential $sourceCredential
$SourceVMName = (Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection).Name
$Datacenter = Get-Datacenter
$Datastore = Get-Datastore
$DataStoreLocation = $Datastore.ExtensionData.info.url
$Datastore = Get-Datastore
# Get-VMHostNetworkAdapter | fl *
Get-VMHostNetworkAdapter | select VMhost, Name, IP, SubnetMask, Mac, DHCPEnabled, DeviceName | Export-Csv C:\VMHostNetworkDetails_$datetime.csv -Delimiter ";"
Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection | select MemorySizeBytes, OperatingSystem, UsedSpacebytes | Export-Csv C:\VMRAmDetails_$datetime.csv -Delimiter ";"
$Global:DefaultVIServers | Select ProductLine,Version,Build, Port | Export-Csv C:\GlobalDetails_$datetime.csv -Delimiter ";"
#(Import-Csv C:\VMHostNetworkDetails_$datetime.csv) + #(Import-Csv C:\VMRAmDetails_$datetime.csv) + #(Import-Csv C:\GlobalDetails_$datetime.csv) | Export-Csv C:\ESxiDetails_$datetime.csv -Delimiter ";"
Note: get-vm does not work for me.
EDIT:
I tried to get the info by using foreach loop, but cannot get IP, SubnetMask, Mac, DHCPEnabled.$VMSysInfo.IPAddressdoes not give me any IP, but Get-VMHostNetworkAdapter | select VMhost, Name, IP, SubnetMask, Mac, DHCPEnabled, DeviceName gives me IP.
$VmInfo = vmware.vimautomation.core\Get-VM
$VMS = ($VmInfo).Name
$VCenter = #()
foreach ($VM in $VMS)
{
$HostServer = (($VmInfo | ? {$_.Name -eq $VM}).Host).Name
$VMSysInfo = Get-VMGuest -VM $VM
$MyObject = New-Object PSObject -Property #{
VMName = $VM
#VMHostName = $VMSysInfo.HostName
VMIP = $VMSysInfo.IPAddress
VMInstalledOS = $VMSysInfo.OSFullName
PowerState = ($VmInfo | ? {$_.Name -eq $VM}).PowerState
NumberOfCPU = ($VmInfo | ? {$_.Name -eq $VM}).NumCpu
MemoryGB = (($VmInfo | ? {$_.Name -eq $VM}).MemoryMB/1024)
VMDataS = (Get-Datastore -VM $VM).Name
#HostServer = (($VmInfo | ? {$_.Name -eq $VM}).Host).Name
#HostCluster = (Get-Cluster -VMHost $HostServer).Name
Datacenter = (Get-Datacenter -VM $vm).Name
#Notes = $vm | Select -ExpandProperty Description
Portgroup = (Get-VirtualPortGroup -VM $vm).Name
}
$VCenter += $MyObject
}
$VCenter | Select VMName,
#{N='VMIPAddress';E={$_.VMIP -join '; '}},
VMInstalledOS, PowerState, NumberOfCPU, MemoryGB,
#{N='VMDataStore';E={$_.VMDataS -join '; '}},
HostServer, HostCluster,Datacenter, Notes, Portgroup |
Export-Csv C:\test.csv -NoTypeInformation -Delimiter ";"
I changed the foreach loop and it works:
$VmInfo = vmware.vimautomation.core\Get-VM
#$VmInfo = (Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection).Name
$VMS = ($VmInfo).Name
$Data = #()
foreach ($VM in $VMS)
{
$Datacenter = Get-Datacenter
$Datastore = Get-Datastore
$SourceIP = ($global:DefaultVIServer).name
$DataStoreLocation = $Datastore.ExtensionData.info.url
$VMNetwork = Get-VMHostNetworkAdapter
$PortalGroup = Get-VirtualPortGroup -VM $vm
$MvmcSourceVirtualMachine = Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection
$VMCustom = New-Object System.Object
$VMCustom | Add-Member -Type NoteProperty -Name DataCenter -Value $Datacenter.Name
$VMCustom | Add-Member -Type NoteProperty -Name DataStoreName -Value $Datastore.Name
$VMCustom | Add-Member -Type NoteProperty -Name DataStoreLocation -Value $DataStoreLocation
$VMCustom | Add-Member -Type NoteProperty -Name NumberOfCPU -Value $VmInfo.NumCpu
$VMCustom | Add-Member -Type NoteProperty -Name PowerState -Value $VmInfo.PowerState
$VMCustom | Add-Member -Type NoteProperty -Name MemoryGB -Value $VmInfo.MemoryGB
$VMCustom | Add-Member -Type NoteProperty -Name VMHost -Value $VMNetwork.VMhost
$VMCustom | Add-Member -Type NoteProperty -Name DHCP -Value $VMNetwork.DHCPEnabled
$VMCustom | Add-Member -Type NoteProperty -Name SubnetMask -Value $VMNetwork.SubnetMask
$VMCustom | Add-Member -Type NoteProperty -Name Client -Value $VMNetwork.Client
$VMCustom | Add-Member -Type NoteProperty -Name IP -Value $SourceIP
$VMCustom | Add-Member -Type NoteProperty -Name MacAddress -Value $VMNetwork.Mac
$VMCustom | Add-Member -Type NoteProperty -Name PortalGroupName -Value $PortalGroup.Name
$VMCustom | Add-Member -Type NoteProperty -Name OperatingSystem -Value $MvmcSourceVirtualMachine.OperatingSystem
$Data += $VMCustom
}
$Data | Export-CSV "C:\ESXiInfo.csv" -Delimiter ";" -NoTypeInformation