Powershell object doesn't add member - powershell

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.

Related

Add a ScriptMethod Helper to query PSCustomObject

I am trying to add some simple helper methods to an existing PSCustomObject.
My goal is to replace something like this:
$Persons.Where{$_.FirstName -like "*Test*"}
With this:
$Persons.GetFirstName("Test")
I am having a lot of trouble figuring out a working ScriptMethod to use with add-member.
Here is my example code, along with all of the variations I have tried so far:
$Persons = [PSCustomObject]#()
$Person1 = [PSCustomObject]#{
FirstName = 'John';
LastName = 'Doe';
Age = 27
}
$Person2 = [PSCustomObject]#{
FirstName = 'Test';
LastName = 'Dummy';
Age = 27
}
$Persons += $Person1
$Persons += $Person2
$Persons
#FirstName LastName Age
#--------- -------- ---
#John Doe 27
#Test Dummy 27
#Get using a regular where method to confirm
$Persons.Where{$_.FirstName -like "*Test*"}
#FirstName LastName Age
#--------- -------- ---
#Test Dummy 27
#Add the Helper Method GetFirstName
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where{$_.FirstName -like "$Args[0]"}}
#Check if the Test record is returned
$Persons.GetFullName("Test")
#Use this to remove the method for the next try
$Persons.PSObject.properties.remove('GetFirstName')
#Other Permutations I have tried
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where($this.FirstName -like "$($Args[0])")}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({FirstName -like $Args[0]})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({FirstName -like $args(0)})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({FirstName -like "$Args[0]"})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({FirstName -like "$($Args[0])"})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({$this.FirstName -like $Args[0]})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({$this.FirstName -like "*$($Args[0])*"})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({$this.FirstName -eq $Args[0]})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({$_.FirstName -like $Args[0]})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where({$_.FirstName -like "$($Args[0])"})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where("FirstName -like ""$($Args[0])""")}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.where("$($_.FirstName) -like ""$($Args[0])""")}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.GetEnumerator().where{FirstName -like $Args[0]}}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.GetEnumerator().where{$this.FirstName -like $Args[0]}}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this.GetEnumerator().where{$_.FirstName -like $Args[0]}}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this | ?{$_.FirstName -like $Args[0]}}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this | ?({$_.FirstName -like $Args[0]})}
add-member -inputobject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {$this | ?({$_.FirstName -like "$($Args[0])"})}
There's one $Args per scope, so $Args inside .Where{ <in here> } does not actually contain the input arguments to the script method - declare a named parameter instead and it'll work:
Add-Member -InputObject $Persons -MemberType ScriptMethod -Name GetFirstName -Value {
param([string]$fnArg)
$this.Where{$_.FirstName -like $fnArg}
} -Force

InputObject is null - Powershell DataTable

I'm attempting to output an object array (of event logs) to a DataTable with the expectation to pipe into SQL.
The basics are:
Get some forwarded events
Process them to pull some required info out
Output to a data table
function Get-Type
{
param($type)
$types = #(
'System.Boolean',
'System.Byte[]',
'System.Byte',
'System.Char',
'System.Datetime',
'System.Decimal',
'System.Double',
'System.Guid',
'System.Int16',
'System.Int32',
'System.Int64',
'System.Single',
'System.UInt16',
'System.UInt32',
'System.UInt64')
if ( $types -contains $type ) {
Write-Output "$type"
}
else {
Write-Output 'System.String'
}
} #Get-Type
function Out-DataTable
{
[CmdletBinding()]
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
Write-Output "test"
foreach ($object in $InputObject)
{
$DR = $DT.NewRow()
foreach($property in $object.PsObject.get_properties())
{
if ($first)
{
$Col = new-object Data.DataColumn
$Col.ColumnName = $property.Name.ToString()
if ($property.value)
{
if ($property.value -isnot [System.DBNull]) {
$Col.DataType = [System.Type]::GetType("$(Get-Type $property.TypeNameOfValue)")
}
}
$DT.Columns.Add($Col)
}
if ($property.Gettype().IsArray) {
$DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1
}
else {
$DR.Item($property.Name) = $property.value
}
}
$DT.Rows.Add($DR)
$First = $false
}
}
End
{
Write-Output #(,($dt))
}
} #Out-DataTable
$allEvents = Get-WinEvent -LogName ForwardedEvents | Where-Object{$_.Id -ne 111}
$outEvents = #()
$dt = $null
foreach ($curEvent in $allEvents){
$curObj = $null
switch ($curEvent.ID) {
4624 {
$curObj = New-Object -TypeName PSObject
Add-Member -InputObject $curObj -MemberType NoteProperty -Name TimeCreated -Value ([datetime]$curEvent.TimeCreated)
Add-Member -InputObject $curObj -MemberType NoteProperty -Name Action -Value $curEvent.TaskDisplayName
Add-Member -InputObject $curObj -MemberType NoteProperty -Name MachineName -Value $curEvent.MachineName
Add-Member -InputObject $curObj -MemberType NoteProperty -Name UserName -Value ((($curEvent.Message).Split([Environment]::NewLine)[36]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name LoginID -Value ((($curEvent.Message).Split([Environment]::NewLine)[40]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name SourceIP -Value ((($curEvent.Message).Split([Environment]::NewLine)[64]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name ID -Value $curEvent.Id
Add-Member -InputObject $curObj -MemberType NoteProperty -Name RecordID -Value $curEvent.RecordID
}
4647 {
$curObj = New-Object -TypeName PSObject
Add-Member -InputObject $curObj -MemberType NoteProperty -Name TimeCreated -Value ([datetime]$curEvent.TimeCreated)
Add-Member -InputObject $curObj -MemberType NoteProperty -Name Action -Value $curEvent.TaskDisplayName
Add-Member -InputObject $curObj -MemberType NoteProperty -Name MachineName -Value $curEvent.MachineName
Add-Member -InputObject $curObj -MemberType NoteProperty -Name UserName -Value ((($curEvent.Message).Split([Environment]::NewLine)[8]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name LoginID -Value ((($curEvent.Message).Split([Environment]::NewLine)[12]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name SourceIP -Value "Not Available"
Add-Member -InputObject $curObj -MemberType NoteProperty -Name ID -Value $curEvent.Id
Add-Member -InputObject $curObj -MemberType NoteProperty -Name RecordID -Value $curEvent.RecordID
}
4778 {
$curObj = New-Object -TypeName PSObject
Add-Member -InputObject $curObj -MemberType NoteProperty -Name TimeCreated -Value ([datetime]$curEvent.TimeCreated)
Add-Member -InputObject $curObj -MemberType NoteProperty -Name Action -Value "Reconnect"
Add-Member -InputObject $curObj -MemberType NoteProperty -Name MachineName -Value $curEvent.MachineName
Add-Member -InputObject $curObj -MemberType NoteProperty -Name UserName -Value ((($curEvent.Message).Split([Environment]::NewLine)[6]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name LoginID -Value ((($curEvent.Message).Split([Environment]::NewLine)[10]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name SourceIP -Value ((($curEvent.Message).Split([Environment]::NewLine)[24]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name ID -Value $curEvent.Id
Add-Member -InputObject $curObj -MemberType NoteProperty -Name RecordID -Value $curEvent.RecordID
}
4800 {
$curObj = New-Object -TypeName PSObject
Add-Member -InputObject $curObj -MemberType NoteProperty -Name TimeCreated -Value ([datetime]$curEvent.TimeCreated)
Add-Member -InputObject $curObj -MemberType NoteProperty -Name Action -Value "Locked"
Add-Member -InputObject $curObj -MemberType NoteProperty -Name MachineName -Value $curEvent.MachineName
Add-Member -InputObject $curObj -MemberType NoteProperty -Name UserName -Value ((($curEvent.Message).Split([Environment]::NewLine)[8]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name LoginID -Value ((($curEvent.Message).Split([Environment]::NewLine)[12]).split(":")[1]).Trim()
Add-Member -InputObject $curObj -MemberType NoteProperty -Name SourceIP -Value "Not Available"
Add-Member -InputObject $curObj -MemberType NoteProperty -Name ID -Value $curEvent.Id
Add-Member -InputObject $curObj -MemberType NoteProperty -Name RecordID -Value $curEvent.RecordID
}
Default { }
}
$outEvents += $curObj
}
$outEvents
$dt = Out-DataTable -InputObject $outEvents
When I run this, the last output of $outEvents lists all of the event objects with the correct details however trying to pipt it into Out-DataTable returns:
Out-DataTable : Cannot bind argument to parameter 'InputObject' because it is null.
At \\server\scripts\Repository\Write-UserLoginEvent\Write-UserLoginEvent.ps1:140 char:38
+ $dt = Out-DataTable -InputObject $outEvents
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [Out-DataTable], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Out-DataTable
I've tried all different methods of formatting the data etc and I can't seem to get this function to accept my custom object array.
If I use a built in function like 'Get-Process' the function works correctly and returns the DataTable so I'm thinking it is something specific to the object I'm returning.
EDIT: Before I posted this, I also moved the DataTable segment into the loop, to attempt to print each event object as an individual DataTable. Hoping to identify where the issue was. It failed immediately on the first object.
So the issue was that I had an un-captured event type that had slipped through.
Because this event was not being formatted correctly there was a single event in the output that would not fit into the DataTable structure, causing the NULL error.
To identify the issue I put an Out-DataTable step inside the loop to process each object individually and in the output I could see that all objects succeeded except one. Tracking down that one I could see that I hadn't catered for that Event ID (8001).

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
}

Is there a way to use a function to determine Add-Member value?

$thisplan = New-Object PSObject
Add-Member -InputObject $thisplan -MemberType NoteProperty -Name PlanID -Value $planid
Add-Member -InputObject $thisplan -MemberType NoteProperty -Name PlanName -Value $plan.name
Add-Member -InputObject $thisplan -MemberType NoteProperty -Name SessionPassword -Value $sessionpass
$schedule = $plan.backupConfiguration.advanceSchedule.periodSchedule
#DAY
add-Member -InputObject $thisplan -MemberType NoteProperty -Name DayRetention -Value $schedule.daySchedule.retentionCount
if ($schedule.daySchedule.retentionCount -gt 0)
{
$dstart = udptime($schedule.daySchedule.dayTime)
}
else
{
$dstart = ""
}
Add-Member -InputObject $thisplan -MemberType NoteProperty -Name DayStart -Value $dstart
########################
is there a way to make a function from the #day section?
This is a small part from my script.

Powershell: Get VM Properties

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