I'm still at the beginning of learning powershell. My goal here is to have a script that pulls SCOM alerts that are one day old, compares the alerts' netbios computer name to a value from a CSV that I will import.
If the ServerName from the CSV Matches the NetbiosName it then adds the Administrator Name to the original Array/Table I created. Currently it does everything I ask of it, but when I have it output the final data it only has the last administrator that was used added to the Admin column instead of the appropriate admin.
NetbiosComputerName : Server
MonitoringObjectDisplayName : Server.Domain
Name : Blah Blah Blah
Severity : Warning
ResolutionState : 0
RepeatCount : 0
Server Adminstrator : Admin
NetbiosComputerName : Server
MonitoringObjectDisplayName : Server.Domain
Name : Blah Blah Blah
Severity : Warning
ResolutionState : 0
RepeatCount : 0
Server Adminstrator : Admin
On the Second output the Admin should instead reflect the admin for that particular server and not very same one.
Here is my code.
# Load SCOM snap-in
add-pssnapin "Microsoft.EnterpriseManagement.OperationsManager.Client";
$server = "RMSSERVER"
# Connect to OpsMgr SDK - change management server to your RMS
new-managementGroupConnection -ConnectionString:RMSSERVER.domain;
set-location "OperationsManagerMonitoring::";
$Date = (Get-Date).adddays(-1)
$ScomAlert = get-alert | where {($_.ResolutionState -eq 0) -and ($_.TimeRaised -gt $Date) } | Select NetbiosComputerName,MonitoringObjectDisplayName, Name,Severity, ResolutionState, RepeatCount
$Administrators = Import-CSV "C:\Script\SCOM\admin.csv"
$TableSC = $ScomAlert
ForEach ($Alert in $ScomAlert)
{
$NetBios = "$($Alert.NetBiosComputerName)"
$MonObjectName = "$($Alert.MonitoringObjectDisplayName)"
$AlertName = "$($Alert.Name)"
$Severity = "$($Alert.Severity)"
$ResState = "$($Alert.ResolutionState)"
$RepCount = "$($Alert.RepeatCount)"
ForEach ( $Admin in $Administrators )
{
$ServerName = "$($Admin.ServerName)"
$ServerAdmin = "$($Admin.AdminName)"
if($ServerName -eq $NetBios)
{
$ServerAdministrator = $ServerAdmin
}
}
$TableSC | Add-Member -MemberType NoteProperty -Name "Server Adminstrator" -Value $ServerAdministrator -Force
}
$TableSC | Add-Member -MemberType NoteProperty -Name "Server Adminstrator" ...
The above line replaces the property Server Administrator in all items of the collection $TableSC with the given value.
If you want each item updated with the respective administrator you need something like this (untested):
$Administrators = #{}
Import-Csv "C:\Script\SCOM\admin.csv" | % {
$Administrators[$_.ServerName] = $_.AdminName
}
$TableSC = $ScomAlert | select NetBiosComputerName,
MonitoringObjectDisplayName, Name, Severity, ResolutionState, RepeatCount,
#{n="Server Administrator";e={$Administrators[$_.NetBiosComputerName]}}
Related
I have a text file that has many instances of 10 lines per object. I will like to scan these 10 lines to check if status=failure then pull in Account ID for that failure. Here is a sample of text file:
AccountID : 123_123
Safe : test1
address : xxx.xxx.xxx.xxx
userName : frank
name : frank#xxx.xxx.xxx.xxx
platformId : test
secretType : password
platformAccountProperties : #{Location=home; Owner=Me; Function=switch; Type=user; Port=22}
secretManagement : #{automaticManagementEnabled=True; status=success; lastModifiedTime=1590499693}
createdTime : 5/26/2020 1:28:13 PM
AccountID : 321_321
Safe : test2
address : xxx.xxx.xxx.xxx
userName : ralph
name : ralph#xxx.xxx.xxx.xxx
platformId : test
secretType : password
platformAccountProperties : #{Location=home; Owner=Me; Function=switch; Type=user; Port=22}
secretManagement : #{automaticManagementEnabled=False; manualManagementReason=(CPM)MaxRetries; status=failure; lastModifiedTime=1590499684}
createdTime : 5/26/2020 1:28:04 PM
Notice on secretManagement line status=failure, I need to scan each section to pull down AccountID for that failure, I have tried several ways to do this but I get no luck on it as I am not constructing it correctly. Any ideas on how to do this correctly?
Welcome to SO!
I believe that the following script should work provided that the formatting in your example is always the same.
# Read the file content.
$fileContent = Get-Content C:\tmp\overflow\63004109\data.txt
# Remove all empty lines from the array.
$fileContent = $fileContent | ? { $_ -ne "" }
for ($i = 0; $i -lt $fileContent.Length; $i++) {
$obj = New-Object -TypeName psobject
for ($x = $i; $x -lt ($i+10); $x++) {
$splt = $fileContent[$x].Split(":")
$obj | Add-Member -MemberType NoteProperty -Name $splt[0].Trim() -Value $splt[1].Trim()
}
# Check if the 'secretManagement' status was a 'failure'.
if (($obj.secretManagement -replace '#{','' -replace '}','' -replace '; ',"`n" | ConvertFrom-StringData).Status -eq "failure") {
# Here is where you want to do something with the accounts that failed.
$obj.AccountID + ": " + ($obj.secretManagement -replace '#{','' -replace '}','' -replace '; ',"`n" | ConvertFrom-StringData).Status
}
$i += 9
}
I have some basic Powershell knowledge and i am trying to revise an existing script on our Service Desk to make a shared mailbox in Exchange 2010.
The current version was setup so the user can input the database to assign the mailbox to.
The revised version i am trying to do is suppose to pull the Databases and display the size of each database. Then the idea is the user can simply input a number value to represent a database, rather than writing out the whole database.
So after doing some research i tried out the following;
$mailboxname=Read-Host “Enter mailbox name”
$alias=Read-Host “Enter Email Alias”
$User=$alias + "#domain.com"
Get-MailboxDatabase -Server "Server" -Status | Where-Object {$_.name -like "Database*"} | Sort-Object -Descending -Property #{Expression = "name"; Descending = $true} | Select Name,Databasesize
$script:ChosenDatabase=Get-MailboxDatabase
function Get-MailboxDatabase
{
$database=Read-Host "Enter database using a value of 1 to 4 to add the mailbox to"
Switch ($database)
{
1 {$Chosendatabase="Database-1"}
2 {$Chosendatabase="Database-2"}
3 {$Chosendatabase="Database-3"}
4 {$Chosendatabase="Database-4"}
}
return $Chosendatabase
}
New-mailbox -shared -Name $mailboxname -alias $alias -UserPrincipalName $User -OrganizationalUnit "Domain.com/Resources-OU" -Database $Chosendatabase
Get-mailbox -Identity $User | ft DisplayName,Database
read-host "hit enter to close window"
This kinda works, but it doesn't show the Mailbox Database and as can be seen in the example below it did a double up of the readhost to enter the database
Enter mailbox name: testscript2
Enter Email Alias: testscript2
Enter database using a value of 1 to 4 to add the mailbox to: 2
Enter database using a value of 1 to 4 to add the mailbox to: 2
Name Alias ServerName ProhibitSendQuota
---- ----- ---------- -----------------
testscript2 testscript2 Server unlimited
DisplayName Database
----------- --------
testscript2 Database-2
hit enter to close window:
So i found Show output before Read-Host, which i tried out to see if this will help show the mailboxdatabase before inputting a value.
Changed;
Get-MailboxDatabase -Server "Server" -Status | Where-Object {$_.name -like "Database*"} | Sort-Object -Descending -Property #{Expression = "name"; Descending = $true} | Select Name,Databasesize
To;
$getDB=Get-MailboxDatabase -Server "Server" -Status | Where-Object {$_.name -like "Database*"} | Sort-Object -Descending -Property #{Expression = "name"; Descending = $true} | Select Name,Databasesize | Out-String;
Write-Host $getDB
But got the following errors
Enter mailbox name: testScript
Enter Email Alias: testscript
Name DatabaseSize
---- ------------
Database-4 762.8 GB
Database-3 376.3 GB
Database-2 249.3 GB
Database-1 829.8 GB
Cannot process argument transformation on parameter 'Database'. Cannot convert the
"System.Collections.ArrayList" value of type
"System.Collections.ArrayList" to type "Microsoft.Exchange.Configuration.Tasks.DatabaseIdParameter".
+ CategoryInfo : InvalidData: (:) [New-Mailbox], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,New-Mailbox
+ PSComputerName : Domain.com
The operation couldn't be performed because object 'testscript#domain.com' couldn't be found on
'Domain.com'.
+ CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : 8D2D2EF6,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
+ PSComputerName : Domain.com
hit enter to close window:
Is anybody able to help shed some light on what i am doing wrong and why I am getting a double of the read-host.
Figured this problem out awhile ago and thought to post the solution here.
My mistake was the function was incorrect and shouldn't of been named
function Get-MailboxDatabase
This caused the issue as i was creating a function using an existing cmdlet name (DERP)
I changed my script to the following
$data = Get-MailboxDatabase -Server "Server" -Status | Where-Object {$_.name -like "DATABASE*"} | Sort-Object -Property #{Expression = "name"} | Select Name,Databasesize | ft | Out-String
function WORK
{
Write-host $data
Write-host "Pick the database with the lowest size"
Write-host
$database=Read-Host "Enter the database using a value of 1 to 4 to add the mailbox to"
Switch ($database)
{
1 {$Chosendatabase="DATABASE-1"}
2 {$Chosendatabase="DATABASE-2"}
3 {$Chosendatabase="DATABASE-3"}
4 {$Chosendatabase="DATABASE-4"}
}
return $Chosendatabase
}
$date=Get-Date -format d
$mailboxname=Read-Host “Enter the mailbox name”
$alias=Read-Host “Enter Email Alias”
$User=$alias + "#domain.com"
$ticket=Read-Host "Enter the Ticket number"
$notes="Mailbox created - $ticket - $date"
Read-Host "hit enter to Continue"
$script:ChosenDatabase = WORK
New-mailbox -shared -Name $mailboxname -alias $alias -UserPrincipalName $User -OrganizationalUnit "domain.com/Resources-OU" -Database $Chosendatabase
Set-user -identity $alias -notes "$Notes"
##This command is to make sure a copy of sent emails are stored on the shared mailbox as well as the senders mailbox
Set-MailboxSentItemsConfiguration -Identity $alias -SendAsItemsCopiedTo SenderAndFrom -SendOnBehalfOfItemsCopiedTo SenderAndFrom
##bring back confirmation the script has done as tended
Get-mailbox -Identity $User | ft DisplayName,Database
Get-mailboxsentitemsconfiguration -Identity $alias
read-host "hit enter to close window"
This has been working fine for us for the past few months
I have been struggling to come up with a working solution for days on this
What am I trying to achieve?
Foreach ($item in $webApps){
$WebAppConfig = (Get-AzureRmResource -ResourceType Microsoft.Web/sites/config -ResourceName $item -ResourceGroupName $resourceGroup -ApiVersion $APIVersion)
}
The issue is that "-resourceName" will not accept objects, but rather only a string
I am looking for a way to take the output of the following command, convert it to a string, so that it can satisfy –ResourceName, and loop through each item in the string
$webApps = (Get-AzureRmResourceGroup -Name $resourceGroup | Get-AzureRmWebApp).name
This returns a nice list of Azure WebApps that exist in a specified ResourceGroup, however they are in object form, which –ResourceName will not take
I have tried several ways to convert the output of $webApps to a string, add a comma to the end, then do a –split ',' but nothing seems to work for properly, where –ResourceName will accept it
Method 1:
[string]$webAppsArrays =#()
Foreach ($webApp in $webApps){
$webAp+',' -split ','
}
Method 2:
$
webApps | ForEach-Object {
$webApp = $_ + ","
Write-Host $webApp
}
Method 3:
$csvPath2 = 'C:\Users\Giann\Documents\_Git Repositorys\QueriedAppList2.csv'
$webApps = (Get-AzureRmResourceGroup -Name $resourceGroup | Get-AzureRmWebApp).name | out-file -FilePath $csvPath1 -Append
$csvFile2 = import-csv -Path $csvPath1 -Header Name
This ouputs a list in a CSV, however these are still objects, so I cannot pass each item into –ResourceName
I am going in circles trying to make the below a repeatable, looping script
The desired end result would be to use the below script, with an array of webApps, being queried from the provided resource group variable:
Any help would be greatly appreciated for how to use this script, but pull a dynamic list of WebApps from a specified Resource Group, keeping in mind the -ResourceName "String" restrictions in the $WebAppConfig variable
Here is the original script to create IP Restrictions for 1 Web App and 1 Resource Group, using properties from a CSV file:
#Create a Function to create IP Restrictions for 1 Web App and 1 Resource Group, using properties from the CSV file:
#Variables
$WebApp = ""
$resourceGroup =""
$subscription_Id = ''
#Login to Azure
Remove-AzureRmAccount -ErrorAction SilentlyContinue | Out-Null
Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Subscription $subscription_Id
Function CreateIpRestriction {
Param (
[string] $name,
[string] $ipAddress,
[string] $subnetMask,
[string] $action,
[string] $priority
)
$APIVersion = ((Get-AzureRmResourceProvider -ProviderNamespace Microsoft.Web).ResourceTypes | Where-Object ResourceTypeName -eq sites).ApiVersions[0]
$WebAppConfig = (Get-AzureRmResource -ResourceType Microsoft.Web/sites/config -ResourceName $WebApp -ResourceGroupName $ResourceGroup -ApiVersion $APIVersion)
$ipRestriction = $WebAppConfig.Properties.ipSecurityRestrictions
$ipRestriction.name = $name
$ipRestriction.ipAddress = $ipAddress
$ipRestriction.subnetMask = $subnetMask
$ipRestriction.action = $action
$ipRestriction.priority = $priority
return $ipRestriction
}
#Set csv file path:
$csvPath5 = 'C:\Users\Giann\Documents\_Git Repositorys\ipRestrictions5.csv'
#import CSV Contents
$ipRestrictionArray = Import-Csv -Path $csvPath5
$ipRestrictions = #()
foreach($item in $ipRestrictionArray){
Write-Host "Adding ipRestriction properties for" $item.name
$newIpRestriction = CreateIpRestriction -name $item.name -ipAddress $item.ipAddress -subnetMask $item.subnetMask -action $item.action -priority $item.priority
$ipRestrictions += $newIpRestriction
}
#Set the new ipRestriction on the WebApp
Set-AzureRmResource -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/config -ResourceName $WebApp/web -ApiVersion $APIVersion -PropertyObject $ipRestrictions
As continuation on the comments, I really need multiline, so here as an answer.
Note that I cannot test this myself
This page here shows that the Set-AzureRmResource -Properties parameter should be of type PSObject.
(instead of -Properties you may also use the alias -PropertyObject)
In your code, I don't think the function CreateIpRestriction returns a PSObject but tries to do too much.
Anyway, try like this:
Function CreateIpRestriction {
Param (
[string] $name,
[string] $ipAddress,
[string] $subnetMask,
[string] $action,
[string] $priority
)
# There are many ways to create a PSObject (or PSCustomObject if you like).
# Have a look at https://social.technet.microsoft.com/wiki/contents/articles/7804.powershell-creating-custom-objects.aspx for instance.
return New-Object -TypeName PSObject -Property #{
name = $name
ipAddress = $ipAddress
subnetMask = $subnetMask
action = $action
priority = $priority
}
}
#Set csv file path:
$csvPath5 = 'C:\Users\Giann\Documents\_Git Repositorys\ipRestrictions5.csv'
#import CSV Contents
$ipRestrictionArray = Import-Csv -Path $csvPath5
# create an new array of IP restrictions (PSObjects)
$newIpRestrictions = #()
foreach($item in $ipRestrictionArray){
Write-Host "Adding ipRestriction properties for" $item.name
$newIpRestrictions += (CreateIpRestriction -name $item.name -ipAddress $item.ipAddress -subnetMask $item.subnetMask -action $item.action -priority $item.priority )
}
# here we set the restrictions we collected in $newIpRestrictions in the $WebAppConfig.Properties.ipSecurityRestrictions array
$APIVersion = ((Get-AzureRmResourceProvider -ProviderNamespace Microsoft.Web).ResourceTypes | Where-Object ResourceTypeName -eq sites).ApiVersions[0]
$WebAppConfig = (Get-AzureRmResource -ResourceType Microsoft.Web/sites/config -ResourceName $WebApp -ResourceGroupName $ResourceGroup -ApiVersion $APIVersion)
$WebAppConfig.Properties.ipSecurityRestrictions = $newIpRestrictions
$WebAppConfig | Set-AzureRmResource -ApiVersion $APIVersion -Force | Out-Null
The code above will replace the ipSecurityRestrictions by a new set. You may want to consider first getting them and adding to the already existing list.
I found examples for Getting, Adding and Removing ipSecurityRestrictions here, but I can imagine there are more examples to be found.
Hope that helps.
Having issues getting this script running. Err. Cannot index into a null array
any ideas would be a great help. I've looked at verbose logging but I'm not sure how to output compute methods to find the contents. Obviously it appears to be empty but for investigation purposes at least it would be a start.
$rgname = "xxxxxx"
$subscriptionname = "xxxxxx"
$vmname = "xxxxxx"
# Get the VM we need to configure
$vm = Get-AzureRmVM -ResourceGroupName $rgname -Name $vmname
Write-host "$vm"
# Get the name of the first NIC in the VM
$nic = Get-AzureRmNetworkInterface -ResourceGroupName $rgname -Name (Get-AzureRmResource -ResourceId $vm.NetworkInterfaceIDs[0]).ResourceName
$nsg = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $rgname -Name (Get-AzureRmResource -ResourceId $nic.NetworkSecurityGroup.Id).Name
$nameAndIPArray = #(("ipname1","ipname2","ipname3","ipname4",ipname5"),
("ip1,"ip2","ip3","ip4","ip5"))
#LOOP THE ARRAY AND SET DESCRIPTION AND IP VARIABLE FOR COMMAND
$priority = 1010
for ($i=0;$i -lt $nameAndIPArray[0].length; $i++) {
$nameAndIPArray[0][$i] + " " + $nameAndIPArray[1][$i]
$nsg | Add-AzureRmNetworkSecurityRuleConfig -Name $nameAndIPArray[0][$i] -Description $nameAndIPArray[0][$i] -Access Allow -Protocol Tcp -Direction Inbound -Priority $priority -SourceAddressPrefix $nameAndIPArray[1][$i] -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 443
Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $nsg
$priority = $priority + 10
}
Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine
Cannot index into a null array.
At line:14 char:1
Get-AzureRmResource : Cannot validate argument on parameter 'ResourceId'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
Add-AzureRmNetworkSecurityRuleConfig : Cannot bind argument to parameter 'NetworkSecurityGroup' because it is null.
At line:28 char:12
Set-AzureRmNetworkSecurityGroup : Cannot bind argument to parameter 'NetworkSecurityGroup' because it is null.
At line:29 char:59
I test in my lab, there are some mistakes in your script. Use your script, I could not get $nic and $nsg value.$vm does not have the attribute NetworkInterfaceIDs[0], so you could not use like this. The line $nameAndIPArray loses ". The correct usage should be like below:
$nameAndIPArray = #(("ipname1","ipname2","ipname3","ipname4","ipname5"),
("ip1","ip2","ip3","ip4","ip5"))
I modify your script, I get $nsg by using resource group name and nsg name. You could find them on Portal, it works for me.
$nsg= Get-AzureRmNetworkSecurityGroup -ResourceGroupName <resource group name> -Name "<NSG name>"
$nameAndIPArray = #(("ipname1","ipname2","ipname3","ipname4","ipname5"),
("10.0.0.4","10.0.0.5","10.0.0.6","10.0.0.7","10.0.0.8"))
$priority = 1010
for ($i=0;$i -lt $nameAndIPArray[0].length; $i++) {
$nameAndIPArray[0][$i] + " " + $nameAndIPArray[1][$i]
$nsg | Add-AzureRmNetworkSecurityRuleConfig -Name $nameAndIPArray[0][$i] -Description $nameAndIPArray[0][$i] -Access Allow -Protocol Tcp -Direction Inbound -Priority $priority -SourceAddressPrefix $nameAndIPArray[1][$i] -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 443
Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $nsg
$priority = $priority + 10
}
Replace correct value to your script.
I assume this is the line that is empty, so you are not getting any vms back:
$vm = Get-AzureRmVM -ResourceGroupName $rgname -Name $vmname
so, check the $vm variable and if some vm's exist with those parameters.
I am trying to build a report file collecting data from various sources.
I have built a reporting structure like this:
$Data = import-csv "some CSV FILE"
<#
csv file must look like this
hostname,IP
server1,192.168.1.20
#>
Then I am building an array object, prepopulated with "initial values", and I attach it to my $data variable
$Ids = ('7.1.1.1','7.1.1.2')
$CheckObj= #()
foreach ($id in $IDs) {
$row = "" | Select-Object CheckID,CheckData,CheckDataRaw
$row.CheckID = $id
$row.CheckData = "NotChecked"
$CheckObj+= $row
}
$Data = $Data | Select *,CheckData
$data | % {$_.CheckData = $CheckObj}
The resulting object is:
hostname : server1
ip : 192.168.1.20
CheckData : {#{CheckID=7.1.1.1; CheckData=NotChecked; CheckDataRaw=},
#{CheckID=7.1.1.2; CheckData=NotChecked; CheckDataRaw=}}
All is well until I want to do this:
$FinalReport = $data | Select-Object -Property * -ExpandProperty Checkdata
I get all these errors, which let's say I can ignore...
Select-Object : The property cannot be processed because the property
"CheckData" already exists.
At line:1 char:24
+ ... lReport = $data | Select-Object -Property * -ExpandProperty Checkdata
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (#{hostname=serv...ystem.Objec
t[]}:PSObject) [Select-Object], PSArgumentException
+ FullyQualifiedErrorId : AlreadyExistingUserSpecifiedPropertyExpand,Micro
soft.PowerShell.Commands.SelectObjectCommand
BUT, an entire set of other variable gets altered, like:
$data | fl
hostname : server1
ip : 192.168.1.1
CheckData : {#{CheckID=7.1.1.1; CheckData=NotChecked; CheckDataRaw=;
hostname=server1; ip=192.168.1.1}, #{CheckID=7.1.1.2;
CheckData=NotChecked; CheckDataRaw=; hostname=server1;
ip=192.168.1.1}}
aswell as the $CheckObj variable
$CheckObj
CheckID : 7.1.1.1
CheckData : NotChecked
CheckDataRaw :
hostname : server1
ip : 192.168.1.1
CheckID : 7.1.1.2
CheckData : NotChecked
CheckDataRaw :
hostname : server1
ip : 192.168.1.1
This is totally unintended on my side...
Can someone clarify what I am doing wrong?
I am using powershell 5.0 on Windows 7.
All testing was done using powershell_ise, and I didn't change any of the powershell defaults
My expected result would be for the $Final Report variable to contain the expanded content, not all the variables I used in the process...
It seems, after a bit more digging I understood, to some extent why this is occurring.
I am using simple $b = $a assignments, which appear to be a form of shallow copy. So any change in $b also impacts object $a and vice-versa.
For my purpose I need distinct copies of the data, it seems the solution is to do a deep copy, similar to the solution of this post:
PowerShell copy an array completely
So the working code, which gives me the desired result would be:
Function Copy-Object ($Source,[switch]$DeepCopy) {
# Serialize and Deserialize data using BinaryFormatter
if ($DeepCopy) {
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $Source)
$ms.Position = 0
#Deep copied data
$Target = $bf.Deserialize($ms)
$ms.Close()
Write-Output $Target
}
Else {
Write-Output $Source
}
}
$Data = "" | select hostname,IP
$data.Hostname = "server1"
$data.IP = "192.168.1.10"
$Ids = ('7.1.1.1','7.1.1.2')
$CheckObj= #()
foreach ($id in $IDs) {
$row = "" | Select-Object CheckID,CheckData,CheckDataRaw
$row.CheckID = $id
$row.CheckData = "NotChecked"
$CheckObj += $row
}
$Data = Copy-Object -source $Data -DeepCopy | Select *,CheckData2
$Data | % {$_.CheckData2 = Copy-Object -source $CheckObj -DeepCopy}
$FinalReport = Copy-Object -source $Data -DeepCopy | Select-Object -Property hostname,IP -ExpandProperty Checkdata2
$FinalReport | ft
output being:
CheckID CheckData CheckDataRaw hostname IP
------- --------- ------------ -------- --
7.1.1.1 NotChecked server1 192.168.1.10
7.1.1.2 NotChecked server1 192.168.1.10