Powershell Group Array - arrays

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)" }
}

Related

PNPUtil retrieve each driver and add to array with PSObject

Using Powershell I retrieve all third party drivers installed using:
$PNPDrivers = PNPUtil /Enum-Drivers
The format of the information retrieved are as followed:
Microsoft PnP Utility
Published Name: oem19.inf
Original Name: apollolakesystem.inf
Provider Name: INTEL
Class Name: Systemenheter
Class GUID: {4d36e97d-e325-11ce-bfc1-08002be10318}
Driver Version: 07/18/1968 10.1.17.1
Signer Name: Microsoft Windows Hardware Compatibility Publisher
Published Name: oem20.inf
Original Name: avotonsystem.inf
Provider Name: INTEL
Class Name: Systemenheter
Class GUID: {4d36e97d-e325-11ce-bfc1-08002be10318}
Driver Version: 07/18/1968 10.1.3.1
Signer Name: Microsoft Windows Hardware Compatibility Publisher
I'm trying to make a foreach loop so that each driver are added to an array with PSObject so that I can fetch required information later on in the script.
I have tried so many combinations but never succeeded.
Right now I have tried a regex expression and group each row in order to specify each value but I don't get any data what so ever.
Below is the Regex expression I have used which seems to work?
After that I've tried to follow the information from this link: Parsing Text with PowerShell
Just changing the information to match my code:
$Pattern = "
^(?<PublishedName>Published Name:.*)
^(?<OriginalName>Original Name:.*)
^(?<ProviderName>Provider Name:.*)
^(?<ClassName>Class Name:.*)
^(?<ClassGUID>Class GUID:.*)
^(?<DriverVersion>Driver Version:.*)
^(?<SignerName>Signer Name:.*)
"
$PNPDrivers |
Select-String -Pattern $Pattern |
Foreach-Object {
# here we access the groups by name instead of by index
$PublishedName, $OriginalName, $ProviderName, $ClassName, $ClassGUID, $DriverVersion, $SignerName = $_.Matches[0].Groups['PublishedName', 'OriginalName', 'ProviderName', 'ClassName', 'ClassGUID', 'DriverVersion', 'SignerName'].Value
[PSCustomObject] #{
PublishedName = $PublishedName
OriginalName = $OriginalName
ProviderName = $ProviderName
ClassName = $ClassName
ClassGUID = $ClassGUID
DriverVersion = $DriverVersion
SignerName = $SignerName
}
}
But no data is printed out so I must be missing some but I don't manage to find what.
How can I do to retrieve the data and for each driver use it?
Second try
The code below gives me all values (I think) but it splits it to one row each.
I guess this is because it doesn't match all rexeg:s at the same time.
Can this be changed?
$Pattern = "(^(?<PublishedName>^Published Name:\s*([^\n\r]*)))|(^(?<OriginalName>^Original Name:\s*([^\n\r]*)))|(^(?<ProviderName>^Provider Name:\s*([^\n\r]*)))|(^(?<ClassName>^Class Name:\s*([^\n\r]*)))|(^(?<ClassGUID>^Class GUID:\s*([^\n\r]*)))|(^(?<DriverVersion>^Driver Version:\s*([^\n\r]*)))|(^(?<SignerName>^Signer Name:\s*([^\n\r]*)))"
$PNPDrivers |
Select-String -Pattern $Pattern -AllMatch |
Foreach-Object {
# here we access the groups by name instead of by index
$PublishedName, $OriginalName, $ProviderName, $ClassName, $ClassGUID, $DriverVersion, $SignerName = $_.Matches[0].Groups['PublishedName', 'OriginalName', 'ProviderName', 'ClassName', 'ClassGUID', 'DriverVersion', 'SignerName'].Value
[PSCustomObject] #{
PublishedName = $PublishedName -replace "Published Name: ",""
OriginalName = $OriginalName -replace "Original Name: ",""
ProviderName = $ProviderName -replace "Provider Name: ",""
ClassName = $ClassName -replace "Class Name: ",""
ClassGUID = $ClassGUID -replace "Class GUID: ",""
DriverVersion = $DriverVersion -replace "Driver Version: ",""
SignerName = $SignerName -replace "Signer Name: ",""
}
}
Third try
Almost there! So close!
You are the man postanote!
Since I am going to loop through a package of drivers in our SCCM enviroment working with [PSCustomObject] seems to be the right way to do it.
Although the problem that persists seems to be that some rows get "out of sync" and displays wrong value for the column.
Any thoughts on how to correct that?
Fourth try
Working code!!
$List = New-Object System.Collections.ArrayList
((PNPUtil /Enum-Drivers |
Select-Object -Skip 2) |
Select-String -Pattern 'Published Name:' -Context 0,7) |
ForEach {
if($PSItem.Context.PostContext[4] -like "*Class Version:*"){
$ClassVersion = $PSItem.Context.PostContext[4] -replace '.*:\s+'
$DriverVersion = $PSItem.Context.PostContext[5] -replace '.*:\s+'
$SignerName = $PSItem.Context.PostContext[6] -replace '.*:\s+'
}else{
$ClassVersion = "N/A"
$DriverVersion = $PSItem.Context.PostContext[4] -replace '.*:\s+'
$SignerName = $PSItem.Context.PostContext[5] -replace '.*:\s+'
}
$y = New-Object PSCustomObject
$y | Add-Member -Membertype NoteProperty -Name PublishedName -value (($PSitem | Select-String -Pattern 'Published Name:' ) -replace '.*:\s+')
$y | Add-Member -Membertype NoteProperty -Name OriginalName -value (($PSItem.Context.PostContext[0]) -replace '.*:\s+')
$y | Add-Member -Membertype NoteProperty -Name ProviderName -value (($PSItem.Context.PostContext[1]) -replace '.*:\s+')
$y | Add-Member -Membertype NoteProperty -Name ClassName -value (($PSItem.Context.PostContext[2]) -replace '.*:\s+')
$y | Add-Member -Membertype NoteProperty -Name ClassGUID -value (($PSItem.Context.PostContext[3]) -replace '.*:\s+')
$y | Add-Member -Membertype NoteProperty -Name ClassVersion -value $ClassVersion
$y | Add-Member -Membertype NoteProperty -Name DriverVersion -value $DriverVersion
$y | Add-Member -Membertype NoteProperty -Name SignerName -value $SignerName
$z = $List.Add($y)
}
Let's say you only what monitors then you can just do this, without using a PSCustomObject at all.
Clear-Host
(PNPUtil /Enum-Drivers /class Display |
Select-Object -Skip 2) |
Select-String -Pattern 'Monitors' -Context 3,4
# Results
<#
Published Name: oem...
Original Name: tp...
Provider Name: L...
> Class Name: Monitors
Class GUID: {4d...
Driver Version: 11...
Signer Name: Micr...
Published Name: oe...
Original Name: tp...
Provider Name: L...
> Class Name: Monitors
Class GUID: {4d36...
Driver Version: 06...
Signer Name: Micros...
#>
# The cherry-pick as needed by index, string, string value, etc..
Clear-Host
((PNPUtil /Enum-Drivers /class Display |
Select-Object -Skip 2) |
Select-String -Pattern 'Monitors' -Context 3,4)[0]
# Results
<#
Published Name: oe...
Original Name: tpl...
Provider Name: L...
> Class Name: Monitors
Class GUID: {4d36e...
Driver Version: 11/...
Signer Name: Microso...
#>
Clear-Host
(PNPUtil /Enum-Drivers /class Display |
Select-Object -Skip 2 |
Select-String -Pattern 'Monitors' -Context 3,4 |
ForEach-Object {$PSItem.Context.PreContext[0]})
# Results
<#
Published Name: oem...
Published Name: oem...
#>
Clear-Host
(PNPUtil /Enum-Drivers /class Display |
Select-Object -Skip 2 |
Select-String -Pattern 'Monitors' -Context 3,4 |
ForEach-Object {$PSItem.Context.PreContext[0] -replace '.*:\s+'})
# Results
<#
oem...
oem...
#>
The above response is from a similar to this one that I and others have already responded to.
Parse pnputil output to published name for specific class
Are you guys in the same course/class, or in the same company doing the same thing to see who can get there first? ;-}
If You want to get just one driver's info at a time, just change that filter string and cherry-pick the line you are after.
Yet, if you really, really, want to use [PSCustomObject], then you can still use the above and refactor to this.
Clear-Host
((PNPUtil /Enum-Drivers /class Display |
Select-Object -Skip 2) |
Select-String -Pattern 'Class Name:' -Context 3,4) |
ForEach {
[PSCustomObject]#{
PublishedName = $PSItem.Context.PreContext[0] -replace '.*:\s+'
OriginalName = $PSItem.Context.PreContext[1] -replace '.*:\s+'
ProviderName = $PSItem.Context.PreContext[2] -replace '.*:\s+'
ClassName = ($PSitem | Select-String -Pattern 'Class Name:') -replace '.*:\s+'
ClassGUID = $PSItem.Context.PostContext[0] -replace '.*:\s+'
DriverVersion = $PSItem.Context.PostContext[1] -replace '.*:\s+'
SignerName = $PSItem.Context.PostContext[2] -replace '.*:\s+'
}
}
# Results
<#
PublishedName : oe...
OriginalName : am...
ProviderName : A...
ClassName : Syst...
ClassGUID : {4d36...
DriverVersion : 02/...
SignerName : Microso...
...
PublishedName : oem...
OriginalName : w...
ProviderName : W...
ClassName : W...
ClassGUID : {849...
DriverVersion : 11/...
SignerName : Microsof...
#>
Or table format:
Clear-Host
((PNPUtil /Enum-Drivers /class Display |
Select-Object -Skip 2) |
Select-String -Pattern 'Class Name:' -Context 3,4) |
ForEach {
[PSCustomObject]#{
PublishedName = $PSItem.Context.PreContext[0] -replace '.*:\s+'
OriginalName = $PSItem.Context.PreContext[1] -replace '.*:\s+'
ProviderName = $PSItem.Context.PreContext[2] -replace '.*:\s+'
ClassName = ($PSitem | Select-String -Pattern 'Class Name:') -replace '.*:\s+'
ClassGUID = $PSItem.Context.PostContext[0] -replace '.*:\s+'
DriverVersion = $PSItem.Context.PostContext[1] -replace '.*:\s+'
SignerName = $PSItem.Context.PostContext[2] -replace '.*:\s+'
}
} |
Format-Table -AutoSize
# Results
<#
PublishedName OriginalName ProviderName ClassName ClassGUID DriverVersion SignerName
------------- ------------ ------------ --------- --------- ------------- ----------
...
#>
Update as per your comment...
sometimes, some drivers apparently also displays a Class Version just
below Class GUID. When it does that row gets out of sync. Is it
possible to, I don't know, using a IF-statement that if PostContext[3]
exists change the order for the PostContext?
... and my response to it.
I played with this use case a bit more can refactored my code to address these potential custom/dynamic fields that can happen per driver.
On my system, I had two customer driver properties:
Extension ID
and
Class Version.
Context-wise, they in the same place, so, I addressed them that way. So, the code pulls the data and uses a custom field to hold the value of either or none. So, this means you need to first discover any such items, and alter the code as needed. Note: I used a Switch block to handle that and IF/then to finalize based on the fields needed in the case.
Clear-Host
# Parse/format PnpUtil output based on JSON details, customize for dynamic fields
$PNPDrivers = PNPUtil /Enum-Drivers
$StringDataRegEx = '.*:\s+'
$RemoveClassNamesRegEx = 'Extension ID|Class Version'
$CSvHeaders = #(
'PublishedName',
'OriginalName',
'ProviderName',
'ClassName',
'ClassGUID',
'ClassVersion_or_ExtensionGUID',
'DriverVersion',
'SignerName'
)
$ClassVersionElements = #(
'Extension ID',
'Class Version',
'Signer Name'
)
$ClassVersionElements |
ForEach {
$ElementString = $PSItem
$ContextID = If ($ElementString -match $RemoveClassNamesRegEx)
{5}
Else {6}
$PNPDrivers |
Select-String -Pattern $ElementString -Context $ContextID |
ForEach {
$DriverData = $PSItem
switch ($ElementString)
{
'Extension ID'
{
[PSCustomObject]#{
PublishedName = $DriverData.Context.PreContext[0] -replace $StringDataRegEx
OriginalName = $DriverData.Context.PreContext[1] -replace $StringDataRegEx
ProviderName = $DriverData.Context.PreContext[2] -replace $StringDataRegEx
ClassName = $DriverData.Context.PreContext[3] -replace $StringDataRegEx
ClassGUID = $DriverData.Context.PreContext[4] -replace $StringDataRegEx
ClassVersion_or_ExtensionID = (
$DriverData |
Select-String -Pattern $ElementString
) -replace $StringDataRegEx
DriverVersion = $DriverData.Context.PostContext[0] -replace $StringDataRegEx
SignerName = $DriverData.Context.PostContext[1] -replace $StringDataRegEx
}
}
'Class Version'
{
[PSCustomObject]#{
PublishedName = $DriverData.Context.PreContext[0] -replace $StringDataRegEx
OriginalName = $DriverData.Context.PreContext[1] -replace $StringDataRegEx
ProviderName = $DriverData.Context.PreContext[2] -replace $StringDataRegEx
ClassName = $DriverData.Context.PreContext[3] -replace $StringDataRegEx
ClassGUID = $DriverData.Context.PreContext[4] -replace $StringDataRegEx
ClassVersion_or_ExtensionID = (
$DriverData |
Select-String -Pattern $ElementString
) -replace $StringDataRegEx
DriverVersion = $DriverData.Context.PostContext[0] -replace $StringDataRegEx
SignerName = $DriverData.Context.PostContext[1] -replace $StringDataRegEx
}
}
'Signer Name'
{
If ($DriverData -NotMatch $RemoveClassNamesRegEx)
{
[PSCustomObject]#{
PublishedName = $DriverData.Context.PreContext[0] -replace $StringDataRegEx
OriginalName = $DriverData.Context.PreContext[1] -replace $StringDataRegEx
ProviderName = $DriverData.Context.PreContext[2] -replace $StringDataRegEx
ClassName = $DriverData.Context.PreContext[3] -replace $StringDataRegEx
ClassGUID = $DriverData.Context.PreContext[4] -replace $StringDataRegEx
ClassVersion_or_ExtensionID = 'Property not valid for this driver'
DriverVersion = $DriverData.Context.PreContext[5] -replace $StringDataRegEx
SignerName = (
$DriverData |
Select-String -Pattern $ElementString
) -replace $StringDataRegEx
}
}
}
}
}
} |
Format-Table -AutoSize

Custom Object Export Array and Add to the array

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
}

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.

Start-Job -ScriptBlock: Retrieving an array that is compiled inside the ScriptBlock

I have a Foreach loop inside a ScriptBlock that builds an array.
I cannot figure out how to retrieve the array from the Job once it's finished.
Here is my current code.
$HSMissingEmail = New-Object System.Collections.ArrayList
$HSDataObjects = New-Object System.Collections.ArrayList
$HSMissingEmail = Start-Job -Name HSMissingEmailStatus -ScriptBlock {
param($HSDataObjects, $HSMissingEmail);
foreach ($HSDO in $HSDataObjects) {
$HSDO = $HSDO | Select-Object Name, Location, Telephone, EmailAddress, Comments;
if ($HSDO | Where-Object {$_.EmailAddress -like ""}) {
$HSMissingEmail.Add($HSDO)
}
}
} -HSDataObjects $HSDataObjects -HSMissingEmail $HSMissingEmail | Receive-Job -Name HSMissingEmailStatus
I've also tried the following but it didn't do anything either.
$HSMissingEmail = New-Object System.Collections.ArrayList
$HSDataObjects = New-Object System.Collections.ArrayList
$ScriptBlock =
{
param($HSDataObjects,$HSMissingEmail)
foreach ($HSDO in $HSDataObjects)
{
$HSDO = $HSDO | Select-Object Name, Location, Telephone, EmailAddress, Comments
if ($HSDO | Where-Object {$_.emailaddress -like ""})
{
$HSMissingEmail.Add($HSDO)
}
}
}
Start-Job -Name HSMissingEmailStatus -ScriptBlock $ScriptBlock -HSDataObjects $HSDataObjects -HSMissingEmail $HSMissingEmail
ProgressBar ([REF]$HSMissingEmailStatus)
$HSMissingEmail = Receive-Job -Name HSMissingEmailStatus
Get-job -Name HSMissingEmailStatus | Remove-Job
I have tried many different ways to form the ScriptBlock but none are returning anything to $HSMissingEmail.
Also the second block of code doesn't get the passed data until I make the ScriptBlock all one line, which I'm unsure if this is a default behavior.
How can I retrieve the array?
You need to write the array out to standard out.
$HSMissingEmail = New-Object System.Collections.ArrayList
$HSDataObjects = New-Object System.Collections.ArrayList
$HSMissingEmail = Start-Job -Name HSMissingEmailStatus -ScriptBlock {
param($HSDataObjects, $HSMissingEmail);
foreach ($HSDO in $HSDataObjects) {
$HSDO = $HSDO | Select-Object Name, Location, Telephone, EmailAddress, Comments;
if ($HSDO | Where-Object {$_.EmailAddress -like ""}) {
$HSMissingEmail.Add($HSDO)
}
}
$HSMissingEmail # Drops it out as a result of the script block
} -HSDataObjects $HSDataObjects -HSMissingEmail $HSMissingEmail
Receive-Job -Name HSMissingEmailStatus -Wait # At the appropriate time, or keep cycling until you get it all
As far as the single-line/multiline bit, it might be a problem with not explicitly typing the variable as [ScriptBlock], but I'd have to check.

Resources