Custom Object Export Array and Add to the array - arrays

I am having difficulty understanding what I am missing.
I am trying to do 2 things, I am trying to build a custom object array, then later add to the custom object array with more data. Then Finally Export the full custom object array to a csv. I know I am close but all I am getting is "Object" for the custom object array.
The object appears intact in Add-ArraySiteDefaultvsUserSettings and when it leave that function but then I can not build on the object and it be usefull.
Function Add-DefaultsValidation
{
#New-Object psobject -Property #{IdenTity = '';SiteDefault = '';UserSetting = '';IssueAlert =''}
$DefaultsObject = New-Object Object -TypeName PSObject
Add-Member -MemberType NoteProperty -Name SiteCode -Value "" -InputObject $DefaultsObject
Add-Member -MemberType NoteProperty -Name Identity -Value "" -InputObject $DefaultsObject
Add-Member -MemberType NoteProperty -Name OU -Value "" -InputObject $DefaultsObject
Add-Member -MemberType NoteProperty -Name SiteDefault -Value "" -InputObject $DefaultsObject
Add-Member -MemberType NoteProperty -Name UserSetting -Value "" -InputObject $DefaultsObject
Add-Member -MemberType NoteProperty -Name IssueAlert -Value "" -InputObject $DefaultsObject
$DefaultsObject
}
Function Add-ArraySiteDefaultvsUserSettings
{
Param ( $OU, $Identity, $SiteCode, $SiteDefaultValue, $UserCurrentSettings, $AlertType )
#SiteDefaultvsUserSettings
[array]$DefaultvsUserSettings = #()
$addObject = Add-DefaultsValidation
$addObject.SiteCode = $SiteCode
$addObject.Identity = $Identity
$addObject.OU = $OU
$addObject.SiteDefault = $SiteDefaultValue
$addObject.UserSetting = $UserCurrentSettings
$addObject.IssueAlert = $AlertType
$DefaultvsUserSettings += $addObject
#Write-Output $SiteDefaultvsUserSettings
Return $DefaultvsUserSettings
}
foreach ($SkypeSiteDefault in $SkypeSiteDefaults)
{
if ($SkypeSiteDefault.OU -ne $null)
{
$SkypeSiteDefault.'Site Code'
$SkypeSiteDefault.RegistrarPool
$SkypeUsersRegistrarInvalid = Get-CsUser -ResultSize unlimited -ou $SkypeSiteDefault.OU | Where-Object {$_.RegistrarPool.FriendlyName -notlike "*$($SkypeSiteDefault.RegistrarPool)*"} | Select SamAccountName, Registrarpool
if ($SkypeUsersRegistrarInvalid.count -ne 0)
{
foreach ($SkypeUserRegistrarInvalid in $SkypeUsersRegistrarInvalid)
{
$myOU = $SkypeUserRegistrarInvalid.Identity | ForEach-Object{($_ -split "," | Select-Object -Skip 2)}
$UserOU = $myOU -join ','
[array]$SkypeUserInvalidObjectAttribute = #()
$SkypeUserInvalidObjectAttribute =
Add-ArraySiteDefaultvsUserSettings `
-SiteCode $SkypeSiteDefault.'Site Code' `
-Identity $SkypeUserRegistrarInvalid.SamAccountName `
-OU $UserOU `
-SiteDefaultValue $SkypeSiteDefault.RegistrarPool `
-UserCurrentSettings $SkypeUserRegistrarInvalid.Registrarpool.FriendlyName `
-AlertType 'INVALID - REGISTRAR POOL'
If ($SkypeUsersInvalidObjectAttribute.count -eq 0)
{
$SkypeUsersInvalidObjectAttribute = $SkypeUserInvalidObjectAttribute
}
else
{
$SkypeUsersInvalidObjectAttribute += $SkypeUserInvalidObjectAttribute
}
}
}
#Get-CsUser -ResultSize unlimited -ou $SkypeSiteDefault.OU | Where-Object {$_.Registrarpool -ne $SkypeSiteDefault.RegistrarPool} | Select SamAccountName, Registrarpool
$SkypeSiteDefault.'Site Code'
$SkypeSiteDefault.'Dial Plan'
$SkypeSiteDefault.'Site Code'
$SkypeSiteDefault.'Voice Policy'
Write-Host ''
Write-Host ''
}
}
$SkypeUsersInvalidObjectAttribute | Export-CSV "C:\Scriptout\Test.csv"

Parrish - Thank you a lot for your answer: A Class is exactly the solution I needed.
Class ObjectCompare
{
[String] $SiteCode
[String] $Identity
[String] $OU
[String] $SiteDefault
[String] $UserSetting
[String] $IssueAlert
}
Function Add-ArraySiteDefaultvsUserSettings
{
Param ( $OU, $Identity, $SiteCode, $SiteDefaultValue, $UserCurrentSettings, $AlertType )
#SiteDefaultvsUserSettings
[array]$DefaultvsUserSettings = #()
$addObject = New-Object ObjectCompare # Add-DefaultsValidation
$addObject.SiteCode = $SiteCode
$addObject.Identity = $Identity
$addObject.OU = $OU
$addObject.SiteDefault = $SiteDefaultValue
$addObject.UserSetting = $UserCurrentSettings
$addObject.IssueAlert = $AlertType
$DefaultvsUserSettings += $addObject
#Write-Output $SiteDefaultvsUserSettings
Return $DefaultvsUserSettings
}

Related

Powershell error. WriteToServer. column does not allow DBNull.Value

I am using following powershell script to collect server storage information from multiple servers and into the one of the SQL server table.
I am getting an error while executing following powershell script
Error:-
Exception calling "WriteToServer" with "1" argument(s): "Column
'server_name' does not allow DBNull.Value.
Table has only one column with all server names in it. Powershell script grabs server name from database table and collect server storage information. It works for few servers however it fails for few server with above error.
Table
CREATE TABLE [dbo].[server_space_lku](
[server_name] [varchar](50) NOT NULL,
CONSTRAINT [PK_server_lku] PRIMARY KEY CLUSTERED)
I am using following powershell script. How can I fix the issue?
param($destServer, $destDb)
function Get-SqlData
{
param([string]$serverName=$(throw 'serverName is required.'), [string]$databaseName=$(throw 'databaseName is required.'),
[string]$query=$(throw 'query is required.'))
Write-Verbose "Get-SqlData serverName:$serverName databaseName:$databaseName query:$query"
$connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
$da = New-Object "System.Data.SqlClient.SqlDataAdapter" ($query,$connString)
$dt = New-Object "System.Data.DataTable"
[void]$da.fill($dt)
$dt
} #Get-SqlData
function Get-Vol
{
param($computerName)
Get-WmiObject -computername "$ComputerName" Win32_Volume -filter "DriveType=3 AND SystemVolume = $false" |
foreach { add-member -in $_ -membertype noteproperty UsageDT $((Get-Date).ToString("yyyy-MM-dd"))
add-member -in $_ -membertype noteproperty SizeGB $([math]::round(($_.Capacity/1GB),2))
add-member -in $_ -membertype noteproperty FreeGB $([math]::round(($_.FreeSpace/1GB),2))
add-member -in $_ -membertype noteproperty PercentFree $([math]::round((([float]$_.FreeSpace/[float]$_.Capacity) * 100),2)) -passThru} |
select UsageDT, SystemName, Name, Label, SizeGB, FreeGB, PercentFree
}# Get-Vol
function Out-DataTable
{
param($Properties="*")
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
$DR = $DT.NewRow()
foreach ($item in $_ | Get-Member -type *Property $Properties ) {
$name = $item.Name
if ($first) {
$Col = new-object Data.DataColumn
$Col.ColumnName = $name
$DT.Columns.Add($Col)
}
$DR.Item($name) = $_.$name
}
$DT.Rows.Add($DR)
$First = $false
}
End
{
return #(,($dt))
}
}# Out-DataTable
function Write-DataTableToDatabase
{
param($destServer,$destDb,$destTbl,$dt)
$connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;"
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = "$destTbl"
$bulkCopy.WriteToServer($dt)
}# Write-DataTableToDatabase
Get-SqlData $destServer $destDb "SELECT server_name FROM server_space_lku" |
foreach {
#Get just the server name portion if instance name is included
$computerName = $_.server_name -replace "\\.*|,.*"
$dt = Get-Vol $computerName | Out-DataTable
Write-DataTableToDatabase $destServer $destDb 'vol_space' $dt
}

Powershell arrays into html tables

Ok so I have my first ever powershell script and it works exactly how I want it to. The output was just to a txt file and it was bland.
Totally reworked it to give all results into a single array.
mind you there maybe a better way to do this or I may have put too much code so suggestions welcomed....
my end goal is a html with just 2 rows.... Item and Result
this is ran on a machine that will get registry settings, services startup types and local acct status.
I just cant figure out how to do a table and cycle through the arrays.
thanks for your help as it is greatly apprecaited!!!!
# Static array of registry keys
$RegKeys = #("DisableNotificationCenter","AutoConfiURL","HibernateEnabled","HideSCAHealth","NoDriveTypeAutoRun","TurnOffSidebar","EnableBaloonTips","UseDomainNameDevolution","DomainNameDevolutionlevel","*.one.ads","*","SearchOrderConfig","NoAutoRebootWithLoggedOnUsers","DisabledComponents","fAllowToGetHelp","fDenyTSConnections","EnableLUA","dontdisplaylastusername")
#Static array of service names
$Services = #("LanmanServer","MPSSVC","WinDefend","WSCSVC","TRKWKS","NAPAGENT","WUAUSERV")
#Static array of users
$Users = #("Admin","Guest")
#Registry Keys
$dnc = 'HKCU:\Software\Policies\Microsoft\Windows\Explorer'
if (Test-Path $dnc) {$dnc = (Get-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer").DisableNotificationCenter}
else {$dnc = "Key not Found"}
$acu = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
if (Test-Path $acu) {$acu = (Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings").AutoConfigURL}
else {$acu = "Key not Found"}
$he = 'HKLM:\SYSTEM\CurrentControlSet\Control\Power'
if (Test-Path $he) {$he = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Power").HibernateEnabled}
else {$he = "Key not Found"}
$hscah = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer'
if (Test-Path $hscah) {$hscah = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer").HideSCAHealth}
else {$hscah = "Key not Found"}
$ndtar = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer'
if (Test-Path $ndtar) {$ndtar = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer").NoDriveTypeAutoRun}
else {$ndtar = "Key not Found"}
$tos = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Windows\Sidebar'
if (Test-Path $tos) {$tos = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Windows\Sidebar").TurnOffSidebar}
else {$tos = "Key not Found"}
$ebt = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer\Advanced'
if (Test-Path $ebt) {$ebt = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer\Advanced").EnableBaloonTips}
else {$ebt = "Key not Found"}
$udnd = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient'
if (Test-Path $udnd) {$udnd = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient").UseDomainNameDevolution}
else {$udnd = "Key not Found"}
$dndl = 'HKLM:\SYSTEM\CURRENTCONTROLSET\SERVICES\Dnscache\Parameters'
if (Test-Path $dndl) {$dndl = (Get-ItemProperty -Path "HKLM:\SYSTEM\CURRENTCONTROLSET\SERVICES\Dnscache\Parameters").DomainNameDevolutionlevel}
else {$dndl = "Key not Found"}
$oads = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads'
if (Test-Path $oads) {$oads = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads")."*"}
else {$oads = "Key not Found"}
$ads = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads'
if (Test-Path $ads) {$ads = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\")."*"}
else {$ads = "Key not Found"}
$soc = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching'
if (Test-Path $soc) {$soc = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching").SearchOrderConfig}
else {$soc = "Key not Found"}
$narwlou = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'
if (Test-Path $narwlou) {$narwlou = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU").NoAutoRebootWithLoggedOnUsers}
else {$narwlou = "Key not Found"}
$dc = 'HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters'
if (Test-Path $dc) {$dc = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters").DisabledComponents}
else {$dc = "Key not Found"}
$atgh = 'HKLM:\SYSTEM\CurrentControlSet\Control\Remote Assistance'
if (Test-Path $atgh) {$atgh = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Remote Assistance").fAllowToGetHelp}
else {$atgh = "Key not Found"}
$dtsc = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services'
if (Test-Path $dtsc) {$dtsc = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services").fDenyTSConnections}
else {$dtsc = "Key not Found"}
$elua = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System'
if (Test-Path $elua) {$elua = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System").EnableLUA}
else {$elua = "Key not Found"}
$ddlun = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System'
if (Test-Path $ddlun) {$ddlun = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System").dontdisplaylastusername}
else {$ddlun = "Key not Found"}
#Services
$ls = (Get-WmiObject Win32_Service -filter "Name='LanmanServer'").StartMode
$mpssvc = (Get-WmiObject Win32_Service -filter "Name='MPSSVC'").StartMode
$wd = (Get-WmiObject Win32_Service -filter "Name='WinDefend'").StartMode
$wscsvc = (Get-WmiObject Win32_Service -filter "Name='WSCSVC'").StartMode
$trkwks = (Get-WmiObject Win32_Service -filter "Name='TRKWKS'").StartMode
$napagent = (Get-WmiObject Win32_Service -filter "Name='NAPAGENT'").StartMode
$wuauserv = (Get-WmiObject Win32_Service -filter "Name='WUAUSERV'").StartMode
#Local Accounts
$Adm = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True' AND Name='Administrator'"
$Admin = $Adm.Disabled
$Gu = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True' AND Name='Guest'"
$Guest = $Gu.Disabled
#Make individual arrays from each queried information
$RegValues = #($dnc,$acu,$he,$hscah,$ndtar,$tos,$ebt,$udnd,$dndl,$oads,$ads,$soc,$narwlou,$dc,$atgh,$dtsc,$elua,$ddlun)
$ServiceValues = #($ls,$mpssvc,$wd,$wscsvc,$trkwks,$napagent,$wuauserv)
$UsersValues = #($Admin,$Guest)
#Make array of all keys
$RegAll = #($RegKeys[0], $RegValues[0],$RegKeys[1], $RegValues[1],$RegKeys[2], $RegValues[2],$RegKeys[3], $RegValues[3], $RegKeys[4], $RegValues[4], $RegKeys[5], $RegValues[5]
$RegKeys[6], $RegValues[6], $RegKeys[7], $RegValues[7], $RegKeys[8], $RegValues[8], $RegKeys[9], $RegValues[9], $RegKeys[10], $RegValues[10]
$RegKeys[11], $RegValues[11], $RegKeys[12], $RegValues[12], $RegKeys[13], $RegValues[13], $RegKeys[14], $RegValues[14], $RegKeys[15], $RegValues[15]
$RegKeys[16], $RegValues[16], $RegKeys[17], $RegValues[17], $RegKeys[18], $RegValues[18], $Services[0], $ServiceValues[0], $Services[1], $ServiceValues[1]
, $Services[2], $ServiceValues[2], $Services[3], $ServiceValues[3], $Services[4], $ServiceValues[4], $Services[5], $ServiceValues[5], $Services[6], $ServiceValues[6],
$Users[0], $UsersValues[0], $Users[1], $UsersValues[1])
#output to html
$RegAll # | Select #{label='Item';expression={$_}} | ConvertTo-HTML -Fragment -Property 'Item' |Out-File c:\Scripts.html
This is an example which I have used in a script. You can adpt it on your script. Ask when you need help.
$YourArray = #()
#Object one for the array
$test1 = New-Object –TypeName PSObject
$test1 | Add-Member –MemberType NoteProperty –Name Propert_1 –Value "Example1"
$test1 | Add-Member –MemberType NoteProperty –Name Propert_2 –Value "Example2"
$test1 | Add-Member -MemberType NoteProperty -Name Propert_3 -Value "Example3"
#Object two for the array
$test2 = New-Object –TypeName PSObject
$test2 | Add-Member –MemberType NoteProperty –Name Propert_1 –Value "Example_2_1"
$test2 | Add-Member –MemberType NoteProperty –Name Propert_2 –Value "Example_2_2"
$test2 | Add-Member -MemberType NoteProperty -Name Propert_3 -Value "Example_2_3"
$YourArray = $test1,$test2
$beginning = {
#html code the format of the table
#'
<html>
<head>
<title>Report</title>
<STYLE type="text/css">
BODY{background-color:#b0c4de;}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{font-family:SegoeUI, sans-serif; font-size:15; border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:#778899}
TD{font-family:Consolas, sans-serif; font-size:12; border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
tr:nth-child(odd) { background-color:#d3d3d3;}
tr:nth-child(even) { background-color:white;}
</STYLE>
</head>
<h1>Stackoverflow example</h1>
<table>
<tr><th>Propert_1</th><th>Propert_2</th><th>Propert_3</th></tr>
'#
}
#Mapping between Property and table
$process = {
$Propert_1 = $_.Propert_1
$Propert_2 = $_.Propert_2
$Propert_3 = $_.Propert_3
'<tr>'
'<td bgcolor="#33CC33">{0}</td>' -f $Propert_1
'<td bgcolor="#FFFFFF">{0}</td>' -f $Propert_2
'<td bgcolor="#FFFFFF">{0}</td>' -f $Propert_3
'</tr>'
}
$end = {
#'
</table>
</html>
</body>
'#
}
#Export the array in a html sheet
$YourArray | ForEach-Object -Begin $beginning -Process $process -End $end | Out-File -FilePath "U:\Export_Report.html" -Encoding utf8

Using ref in powershell to return values from function

I've function DoWork which creates an object and keeps it in $AllMailboxes variable. Then within that function I execute another function ProcessEmail which is supposed to take $Mailbox out of $AllMailboxes and variable by ref, add couple of fields to it and either update $AllMailboxes or create new $collection which then holds all $Mailbox with updated fields
$collection = #()
function DoWork() {
Get-User -ResultSize Unlimited | Where { $_.RecipientType -eq 'UserMailbox' } | ForEach { $Users = #{} } { $Users[$_.SamAccountName] = $_ }
$AllMailboxes = Get-Mailbox -ResultSize Unlimited | Where { $_.RecipientTypeDetails -eq "UserMailbox" } | ForEach {
$PrimarySmtpDomain = $_.PrimarySmtpAddress.split("#")
New-Object psobject |
Add-Member -PassThru NoteProperty Alias $_.Alias |
Add-Member -PassThru NoteProperty Name $_.Name |
Add-Member -PassThru NoteProperty DisplayName $_.DisplayName
Add-Member -PassThru NoteProperty .... other values
foreach ($mailbox in $allmailboxes) {
$FullEmail = "somestring"
ProcessEmail ([ref] $Mailbox) ($FullEmail)
}
$collection | ft # doesn't display anything
}
function ProcessEmail ([ref] $Mailbox, $FullEmail) {
$RequireAdd = $true
$addresses = $Mailbox.EmailAddresses
foreach ($address in $addresses) {
if ($address -imatch "sip:") { continue }
if ($address -ireplace("smtp:","") -ieq $FullEmail) {
$requireAdd = $false
break
}
$Mailbox | Add-Member -MemberType NoteProperty -Name NewEmailToAdd -Value $FullEmail
$Mailbox | Add-Member -MemberType NoteProperty -Name NewEmailRequiresAdding -Value $RequireAdd
$Mailbox.NewEmailToAdd # displays correctly
$Mailbox.NewEmailRequiresAdding #display correctly
$collection += $Mailbox
}
I've tried multiple approces with ref, without ref, creating separate variables but I can't for some reason make it to display anything in $collection or in other means outsied of ProcessEmail function. I'm sure I'm missing something.
You're making it more complex by using PSReference (which would need you to access the value property). You have no need to here so far.
There's also little need to use that global / script variable except perhaps as an assignment from DoWork as shown in this mock up.
function DoWork {
foreach ($i in (1..100)) {
$psObject = [PSCustomObject]#{
Property1 = 1
Property2 = 2
}
ProcessEmail -Mailbox $psObject -FullEmail $FullEmail
$psObject
}
}
function ProcessEmail {
param(
$Mailbox,
)
$Mailbox | Add-Member NewProperty1 "one"
$Mailbox | Add-Member NewProperty2 "two"
}
$collection = DoWork
Chris
Seems like you are missing scope. Change it to at least script scope, like this:
$script:collection = #()
$script:collection += $Mailbox
I've actually decided to go
function ProcessEmail ($Mailbox, $FullEmail) {
$RequireAdd = $true
$addresses = $Mailbox.EmailAddresses
foreach ($address in $addresses) {
if ($address -imatch "sip:") { continue }
if ($address -ireplace("smtp:","") -ieq $FullEmail) {
$requireAdd = $false
break
}
}
$Mailbox | Add-Member -MemberType NoteProperty -Name NewEmailToAdd -Value $FullEmail
$Mailbox | Add-Member -MemberType NoteProperty -Name NewEmailRequiresAdding -Value $RequireAdd
return ,$mailbox
}
And simply go by:
$Mailbox = ProcessEmail ($Mailbox) ($FullEmail)
$collection += $Mailbox
Seems to work just fine.

Array removed after function?

I am making a script that goes into all servers we're hosting and gets all members of a specific group and the domain name, and then exports it to a file. I'm saving the users and the domain names into two arrays AA (user array) and DA (domain array) AA stands for användararray, and "användare" is users in swedish so it makes sense to me.
I noticed that the export step didn't work, no users or domain names were exported, so I tried to print them in the function. But it doesn't print anything, so I tried to print it in a different location (didn't work). After some experimenting I came to the conlusion that the only place the arrays actually contains any information is inside the foreach loop where I save the users that I find??!
Here is the code
unction GetData([int]$p) {
Write-Host("B")
for ($row = 1; $row -le $UsernamesArray.Length; $row++)
{
if($CloudArray[$row] -eq 1)
{
.
$secstr = New-Object -TypeName System.Security.SecureString
$PasswordsArray[$row].ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UsernamesArray[$row], $secstr
$output = Invoke-Command -computername $AddressArray[$row] -credential $cred -ScriptBlock {
Import-Module Activedirectory
foreach ($Anvandare in (Get-ADGroupMember fjärrskrivbordsanvändare))
{
$AA = #($Anvandare.Name)
$DA = gc env:UserDomain
#$DA + ";" + $Anvandare.Name
$DA + ";" + $AA
}
}
$output
}
}
$DA
$AA
}
function Export {
Write-Host("C")
$filsökväg = "C:\Users\322sien\Desktop\Coolkids.csv"
$ColForetag = "Företag"
$ColAnvandare = "Användare"
$Emptyline = "`n"
$delimiter = ";"
for ($p = 1; $p -le $DomainArray.Length; $p++) {
$ColForetag + $delimiter + $ColAnvandare | Out-File $filsökväg
$DA + $delimiter + $AA | Out-File $filsökväg -Append
}
}
ReadInfo
GetData
Export
Can anyone help me with this? I've sat down with this all day and i cant find a solution.
Your variables $DA and $AA are bound to GetData function, so they live only there. You could make them available inside your script by changing it's scope.
Change this:
$AA = #($Anvandare.Name)
$DA = gc env:UserDomain
To this:
$script:AA = #($Anvandare.Name)
$script:DA = gc env:UserDomain
So they will now be available for other functions inside the script.
Also I found the ways to improve your script, hope you can see the logic:
function GetData([int]$p) {
Write-Host("B")
for ($row = 1; $row -le $UsernamesArray.Length; $row++)
{
if($CloudArray[$row] -eq 1)
{
.
$secstr = New-Object -TypeName System.Security.SecureString
$PasswordsArray[$row].ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UsernamesArray[$row], $secstr
[array]$output = Invoke-Command -computername $AddressArray[$row] -credential $cred -ScriptBlock {
Import-Module Activedirectory
$array = #()
foreach ($Anvandare in (Get-ADGroupMember fjärrskrivbordsanvändare))
{
$object = New-Object PSObject
$object | Add-Member -MemberType NoteProperty -Name AA -Value #($Anvandare.Name)
$object | Add-Member -MemberType NoteProperty -Name DA -Value (gc env:UserDomain)
$object | Add-Member -MemberType NoteProperty -Name Something -Value $DA + ";" + $AA
$array += $object
}
Write-Output $array
}
Write-Output $output
}
}
}
Your function will now output some data.

Powershell Group Array

I have a custom array
$myresults = #()
$w3svcID = $result.ReturnValue -replace "IISWebServer=", ""
$w3svcID = $w3svcID -replace "'", ""
$vdirName = $w3svcID = "/ROOT";
$vdirs = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebVirtualDirSetting"
foreach($vdir in $vdirs)
{
$vPool = $vdir.Apppoolid
$vName = $vdir.Name
$robj = New-Object System.Object
$robj | Add-Member -type NoteProperty -name Path -value $vName
$robj | Add-Member -type NoteProperty -name Pool -value $vPool
$myresults += $robj
}
$myresults | group-object Pool
I'd like to be able to Group the data in the form of a list where the group values (Path) is under the group-by values (Pool); like so:
DefaultAppPool
W3SVC\
W3VSC\1\ROOT\
MyAppPool
W3SVC\1\ROOT\MyVirtual\
Give this a try:
Get-WmiObject IISWebVirtualDirSetting -Namespace root\MicrosoftIISv2 |
Group-Object AppPoolId | Foreach-Object{
$_.Name
$_.Group | Foreach-Object { "`t$($_.Name)" }
}

Resources