Using ForEach-Object on Array of Structs - Powershell - arrays

I'm evolving my Surveillance script, so i can choose a Service/Maintenance Window. Where all errors are ignored between two time intervals.
This is what i got:
Add-Type -TypeDefinition #"
public struct ServiceWindow
{
public int SWStart;
public int SWEnd;
}
"#
[array]$SWArray = New-Object ServiceWindow
$time = Get-Date -Format HHMM
$time
$ActiveBatchVar = "1000-1005;1306-1345;2300-2305"
$ActiveBatchVar = $ActiveBatchVar.Split(";")
For ($i = 0; $i -lt $ActiveBatchVar.Length; $i++)
{
$tempSW = New-Object ServiceWindow
$tempSW.SWStart = $ActiveBatchVar[$i].Split("-")[0]
$tempSW.SWEnd = $ActiveBatchVar[$i].Split("-")[1]
If ($i -eq 0) { $SWArray = $tempSW } else { $SWArray += $tempSW }
}
Write-Host Complete array...
$SWArray
ForEach-Object ($SWArray) {
Get-Date -Format HHMM
If ($time -ge $_.SWStart -and $time -lt $_.SWEnd) {Write-Host Wohoo we have hit a service window service window...}
}
I get an error in my last ForEach-Object loop. and can't figure out what is wrong.
The point is that I would like to check if the current time is between two given times, like "1000-1005".
Anyone got a clue what’s missing, or maybe a way to simplify the whole thing ;)

Ok, a few things here... You really seem to like the Split() method. You may want to look into some alternatives, like this:
$ActiveBatchVar = #(#("1000","1005"),#("1306","1345"),#("2300","2305"))
See what we did there? It's an array of arrays. #() is the array notation. So I have an array, with 3 arrays in it.
I'm not real familliar with structs, but I am familliar with custom objects, so I would use that if it were me. Then you could do something like:
$SWArray = #() #That's an empty array, we'll add things to it now that it exists
ForEach ($Batch in $ActiveBatchVar){
$SWArray += New-Object PSObject -Property #{
SWStart = $Batch[0]
SWEnd = $Batch[1]
}
}
So then we change the last bit so that you are assigning $time just before your next loop to keep it as accurate as possible, and correct the ForEach just a little and the whole thing would look like this:
$ActiveBatchVar = #(#("1000","1005"),#("1306","1345"),#("2300","2305"))
$SWArray = #()
ForEach ($Batch in $ActiveBatchVar){
$SWArray += New-Object PSObject -Property #{
SWStart = $Batch[0]
SWEnd = $Batch[1]
}
}
Write-Host Complete array...
$SWArray
$time = date -f HHmm
ForEach($SW in $SWArray) {
If ($time -ge $SW.SWStart -and $time -lt $SW.SWEnd) {
Write-Host "Wohoo we have hit a service window service window..."
}
}

Minimum changes:
ForEach-Object ($SWArray) {
to
$SWArray | % {
Also your last Write-Host should enclose the message in quoes ie
{Write-Host "Wohoo..."}

ForEach-Object ($SWArray) {}
This is the wrong syntax, you should use the keyword in
Foreach-Object ($array in $SWArray) {}

if you have a small array...
($SWArray).foreach({
Get-Date -Format HHMM
If ($time -ge $_.SWStart -and $time -lt $_.SWEnd)
{Write-Host Wohoo we have hit a service window service window...}
})

Related

Powershell filling array with function calling itself to loop through

tldr; I need to fill an array, which is populated in a function, within constricted language. Until now i found only ways, which are not do able in constricted language.
So basicly i want to loop through the AD and identify looping groups and where users are placed looping wise.
To Achive this i wrote a function which calls itslef. The function returns 4 diffrent objects. These objects are needed to handle the loop.
But the function scope needs to return the value to the script scope ("top most") as otherwise the script will loop infinitly on the first object already.
Unfortunatly this is in constrained language, which means the most common resolves wont work.
Shortend Code Sample
$ReturnValue1 = #()
$ReturnValue2 = #()
$ReturnValue3 = #()
$ReturnValue4 = #()
Function Get-ADInfos
{
Param(
$Entitys
)
foreach($Entity in $Entitys){
$Object = New-Object -TypeName PSObject
if($Entity.objectClass -eq "user"){
if($ReturnValue2.User.distinguishedName -contains $Entity)
#Do Something
$ReturnValue1 += $Object
Write-Host "$Entity is already scanned"
}else{
#Do something
$ReturnValue2 += $didsomething
Get-ADInfos $Values #looping
}
}elseif($Entity.objectClass -eq "group"){
if($ReturnValue4.Group.distinguishedName -contains $Entity){
#Do Something
$ReturnValue3 += $didsomething
}else{
#Do Something
$ReturnValue4 += $didsomething
Get-ADInfos $Values
}
}else{
write-host "finished"
}
}
Full Code for Repro (Older) #Note: To use constrained language for testing.
$User = #()
$Gruppen = #()
$LoopUser = #()
$LoopGroup = #()
Function Get-ADInfos
{
Param(
$Entry
)
#$Entry = Get-ADGroup "Domain Users"
if($Entry.objectClass -eq "user"){
$Entitys = Get-ADPrincipalGroupMembership $Entry
}elseif($Entry.objectClass -eq "group"){
$Entitys = Get-ADGroupMember $Entry
}else{}
foreach($Entity in $Entitys){
if($Entity.objectClass -eq "user"){
if($User.user -contains $Entity){
$Row = "" | Select User, Group
$Row.User = $Entity
$Row.Group = $Entry
$LoopUser += $Row #return to "master" scope
Write-Host "$Entity is already scanned"
}else{
$Row = "" | Select User, Group
$Row.User = $Entity
$Row.Group = $Entry
$User += $Row #return to "master" scope
Write-Host "$Entity is in $group"
Get-ADInfos $Entity
}
}elseif($Entity.objectClass -eq "group"){
if($Groups.group -contains $Entity){
$Row = "" | Select ScannedGroup, ParentGroup
$Row.ScannedGroup = $Entity
$Row.ParentGroup = $Entry
$LoopGroup += $Row #return to "master" scope
Write-Host "$Entity is already scanned"
}else{
$Row = "" | Select Group
$Row.Group = $Entity
$Groups += $Row #return to "master" scope
Write-Host "$Entity scanned"
Get-ADInfos $Entity
}
}else{
write-host "finished"
}
}
}
Get-ADGroup "Domain Users" | Get-ADInfos
PowerShell Arrays are immutable (fixed size collections):
$User = #()
$User.add('item')
MethodInvocationException: Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
This means that -besides the inefficient use of the increase assignment operator (+=)- it will create a new copy of the of array in each child scope when you try to change it:
$User = #()
function Test {
$User += 'Item'
Write-Host 'Child scope:' $User
}
Test
Write-Host 'Parent scope:' $User
Yields:
Child scope: Item
Parent scope:
Instead, I recommend you to use List<T> Class knowing that you can use the List<T>.Add(T) Method and the fact that objects are referenced by default:
$User = [Collections.Generic.List[object]]::new()
function Test { $User.Add('item') }
Test
$User # Yields: item
Addendum
As your script appears to run under constrained language mode, you will not be allowed to use the List<T> type or anything similar you might consider to use native PowerShell HashTables instead. See also: Mutable lists in Constrained Language Mode.
To apply this to your script:
Change all the arrays (that have a shared scope) to hashtables.
e.g.: $User = #() → $User = #{}
Change your assignments.
e.g.: $User += $Row → $User[$User.Count] = $Row
Change the conditions.
e.g.: $User.user -contains $Entity → $User.Values.user -contains $Entity

PowerShell: Passing an ArrayList of Objects into another Script as an Argument

I am trying to pass an ArrayList that contains objects into another PowerShell script to execute something further.
The error message that I am receiving is:
"Cannot process argument transformation on parameter 'al'. Cannot convert the "System.Collections.Hashable System.Collections.Hashable System.Collections.Hashable" value of type "System.String" to type "System.Collections.ArrayList""
In script1.ps1:
$al = New-Object System.Collections.ArrayList
...
$obj = #{"var1"="apple"; "var2"="banana"; "var3"="carrot";}
$al.Add($obj)
...
foreach ($i in $al) {
$temp = $($i.var1)
write-host "$temp" #outputs "apple" correctly
}
invoke-expression -Command "script2.ps1 -al '$al'"
In script2.ps1:
param ([System.Collections.ArrayList]$al)
...
foreach ($i in $al) {
$temp = $($i.var1)
write-host "$temp" #error message
}
For a reason that I'm not familiar with, Invoke-Expression is converting your ArrayList to a HashTable. If you really need an ArrayList in script2.ps1, you can make $al a global variable (see below).
Updated script1.ps1
$al = New-Object System.Collections.ArrayList
$obj = #{"var1" = "apple"; "var2" = "banana"; "var3" = "carrot"; }
$al.Add($obj)
foreach ($i in $al) {
$temp = $($i.var1)
write-host "$temp"
}
$Global:al = $al
invoke-expression -Command "$PSScriptRoot\script2.ps1"
Updated script2.ps1
param()
$Global:al.GetType().FullName
foreach ($i in $Global:al) {
$temp = $($i.var1)
write-host "$temp"
}

Print Array Elements on one line

I'm populating an array variable $array at some point in my code, for example like below
this
is
an
array
varaible
What if, I wanted to print out the array variable like thisisanarrayvariable as one liner
i took the below approach, but i'am not getting any out while the program is hanging
for ($i=0;$i -le $array.length; $i++)
{ $array[$i] }
obviuosly, i dont want to glue them together like $array[0]+$array[1]+$array[2]..
Hope i can get a better answer.
Joining array elements with no separator
Use the -join operator...
$array -join ''
...or the static String.Join method...
[String]::Join('', $array)
...or the static String.Concat method...
[String]::Concat($array)
For all of the above the result will be a new [String] instance with each element in $array concatenated together.
Fixing the for loop
Your for loop will output each element of $array individually, which will be rendered on separate lines. To fix this you can use Write-Host to write to the console, passing -NoNewline to keep the output of each iteration all on one line...
for ($i = 0; $i -lt $array.Length; $i++)
{
Write-Host -NoNewline $array[$i]
}
Write-Host
The additional invocation of Write-Host moves to a new line after the last array element is output.
If it's not console output but a new [String] instance you want you can concatenate the elements yourself in a loop...
$result = ''
for ($i = 0; $i -lt $array.Length; $i++)
{
$result += $array[$i]
}
The += operator will produce a new intermediate [String] instance for each iteration of the loop where $array[$i] is neither $null nor empty, so a [StringBuilder] is more efficient, especially if $array.Length is large...
$initialCapacity = [Int32] ($array | Measure-Object -Property 'Length' -Sum).Sum
$resultBuilder = New-Object -TypeName 'System.Text.StringBuilder' -ArgumentList $initialCapacity
for ($i = 0; $i -lt $array.Length; $i++)
{
$resultBuilder.Append($array[$i]) | Out-Null # Suppress [StringBuilder] method returning itself
}
$result = $resultBuilder.ToString()
Just use
-join $array
which will glue all elements together.

PowerShell: Set-Content having issues with "file already in use"

I'm working on a PowerShell script that finds all the files with PATTERN within a given DIRECTORY, prints out the relevant lines of the document with the PATTERN highlighted, and then replaces the PATTERN with a provided REPLACE word, then saves the file back. So it actually edits the file.
Except I can't get it to alter the file, because Windows complains about the file already being open. I tried several methods to solve this, but keep running into the issue. Perhaps someone can help:
param(
[string] $pattern = ""
,[string] $replace = ""
,[string] $directory ="."
,[switch] $recurse = $false
,[switch] $caseSensitive = $false)
if($pattern -eq $null -or $pattern -eq "")
{
Write-Error "Please provide a search pattern." ; return
}
if($directory -eq $null -or $directory -eq "")
{
Write-Error "Please provide a directory." ; return
}
if($replace -eq $null -or $replace -eq "")
{
Write-Error "Please provide a string to replace." ; return
}
$regexPattern = $pattern
if($caseSensitive -eq $false) { $regexPattern = "(?i)$regexPattern" }
$regex = New-Object System.Text.RegularExpressions.Regex $regexPattern
function Write-HostAndHighlightPattern([string] $inputText)
{
$index = 0
$length = $inputText.Length
while($index -lt $length)
{
$match = $regex.Match($inputText, $index)
if($match.Success -and $match.Length -gt 0)
{
Write-Host $inputText.SubString($index, $match.Index) -nonewline
Write-Host $match.Value.ToString() -ForegroundColor Red -nonewline
$index = $match.Index + $match.Length
}
else
{
Write-Host $inputText.SubString($index) -nonewline
$index = $inputText.Length
}
}
}
Get-ChildItem $directory -recurse:$recurse |
Select-String -caseSensitive:$caseSensitive -pattern:$pattern |
foreach {
$file = ($directory + $_.FileName)
Write-Host "$($_.FileName)($($_.LineNumber)): " -nonewline
Write-HostAndHighlightPattern $_.Line
%{ Set-Content $file ((Get-Content $file) -replace ([Regex]::Escape("[$pattern]")),"[$replace]")}
Write-Host "`n"
Write-Host "Processed: $($file)"
}
The issue is located within the final block of code, right at the Get-ChildItem call. Of course, some of the code in that block is now a bit mangled due to me trying to fix the problem then stopping, but keep in mind the intent of that part of the script. I want to get the content, replace the words, then save the altered text back to the file I got it from.
Any help at all would be greatly appreciated.
Removed my previous answer, replacing it with this:
Get-ChildItem $directory -recurse:$recurse
foreach {
$file = ($directory + $_.FileName)
(Get-Content $file) | Foreach-object {
$_ -replace ([Regex]::Escape("[$pattern]")),"[$replace]")
} | Set-Content $file
}
Note:
The parentheses around Get-Content to ensure the file is slurped in one go (and therefore closed).
The piping to subsequent commands rather than inlining.
Some of your commands have been removed to ensure it's a simple test.
Just a suggestion but you might try looking at the documentation for the parameters code block. There is a more efficient way to ensure that a parameter is entered if you require it and to throw an error message if the user doesn't.
About_throw: http://technet.microsoft.com/en-us/library/dd819510.aspx
About_functions_advanced_parameters: http://technet.microsoft.com/en-us/library/dd347600.aspx
And then about using Write-Host all the time: http://powershell.com/cs/blogs/donjones/archive/2012/04/06/2012-scripting-games-commentary-stop-using-write-host.aspx
Alright, I finally sat down and just typed everything sequentially in PowerShell, then used that to make my script.
It was actually really simple;
$items = Get-ChildItem $directory -recurse:$recurse
$items |
foreach {
$file = $_.FullName
$content = get-content $file
$newContent = $content -replace $pattern, $replace
Set-Content $file $newcontent
}
Thanks for all your help guys.

How to remove item from an array in PowerShell?

I'm using Powershell 1.0 to remove an item from an Array. Here's my script:
param (
[string]$backupDir = $(throw "Please supply the directory to housekeep"),
[int]$maxAge = 30,
[switch]$NoRecurse,
[switch]$KeepDirectories
)
$days = $maxAge * -1
# do not delete directories with these values in the path
$exclusionList = Get-Content HousekeepBackupsExclusions.txt
if ($NoRecurse)
{
$filesToDelete = Get-ChildItem $backupDir | where-object {$_.PsIsContainer -ne $true -and $_.LastWriteTime -lt $(Get-Date).AddDays($days)}
}
else
{
$filesToDelete = Get-ChildItem $backupDir -Recurse | where-object {$_.PsIsContainer -ne $true -and $_.LastWriteTime -lt $(Get-Date).AddDays($days)}
}
foreach ($file in $filesToDelete)
{
# remove the file from the deleted list if it's an exclusion
foreach ($exclusion in $exclusionList)
{
"Testing to see if $exclusion is in " + $file.FullName
if ($file.FullName.Contains($exclusion)) {$filesToDelete.Remove($file); "FOUND ONE!"}
}
}
I realize that Get-ChildItem in powershell returns a System.Array type. I therefore get this error when trying to use the Remove method:
Method invocation failed because [System.Object[]] doesn't contain a method named 'Remove'.
What I'd like to do is convert $filesToDelete to an ArrayList and then remove items using ArrayList.Remove. Is this a good idea or should I directly manipulate $filesToDelete as a System.Array in some way?
Thanks
The best way to do this is to use Where-Object to perform the filtering and use the returned array.
You can also use #splat to pass multiple parameters to a command (new in V2). If you cannot upgrade (and you should if at all possible, then just collect the output from Get-ChildItems (only repeating that one CmdLet) and do all the filtering in common code).
The working part of your script becomes:
$moreArgs = #{}
if (-not $NoRecurse) {
$moreArgs["Recurse"] = $true
}
$filesToDelete = Get-ChildItem $BackupDir #moreArgs |
where-object {-not $_.PsIsContainer -and
$_.LastWriteTime -lt $(Get-Date).AddDays($days) -and
-not $_.FullName.Contains($exclusion)}
In PSH arrays are immutable, you cannot modify them, but it very easy to create a new one (operators like += on arrays actually create a new array and return that).
I agree with Richard, that Where-Object should be used here. However, it's harder to read.
What I would propose:
# get $filesToDelete and #exclusionList. In V2 use splatting as proposed by Richard.
$res = $filesToDelete | % {
$file = $_
$isExcluded = ($exclusionList | % { $file.FullName.Contains($_) } )
if (!$isExcluded) {
$file
}
}
#the files are in $res
Also note that generally it is not possible to iterate over a collection and change it. You would get an exception.
$a = New-Object System.Collections.ArrayList
$a.AddRange((1,2,3))
foreach($item in $a) { $a.Add($item*$item) }
An error occurred while enumerating through a collection:
At line:1 char:8
+ foreach <<<< ($item in $a) { $a.Add($item*$item) }
+ CategoryInfo : InvalidOperation: (System.Collecti...numeratorSimple:ArrayListEnumeratorSimple) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
This is ancient. But, I wrote these a while ago to add and remove from powershell lists using recursion. It leverages the ability of powershell to do multiple assignment . That is, you can do $a,$b,$c=#('a','b','c') to assign a b and c to their variables. Doing $a,$b=#('a','b','c') assigns 'a' to $a and #('b','c') to $b.
First is by item value. It'll remove the first occurrence.
function Remove-ItemFromList ($Item,[array]$List(throw"the item $item was not in the list"),[array]$chckd_list=#())
{
if ($list.length -lt 1 ) { throw "the item $item was not in the list" }
$check_item,$temp_list=$list
if ($check_item -eq $item )
{
$chckd_list+=$temp_list
return $chckd_list
}
else
{
$chckd_list+=$check_item
return (Remove-ItemFromList -item $item -chckd_list $chckd_list -list $temp_list )
}
}
This one removes by index. You can probably mess it up good by passing a value to count in the initial call.
function Remove-IndexFromList ([int]$Index,[array]$List,[array]$chckd_list=#(),[int]$count=0)
{
if (($list.length+$count-1) -lt $index )
{ throw "the index is out of range" }
$check_item,$temp_list=$list
if ($count -eq $index)
{
$chckd_list+=$temp_list
return $chckd_list
}
else
{
$chckd_list+=$check_item
return (Remove-IndexFromList -count ($count + 1) -index $index -chckd_list $chckd_list -list $temp_list )
}
}
This is a very old question, but the problem is still valid, but none of the answers fit my scenario, so I will suggest another solution.
I my case, I read in an xml configuration file and I want to remove an element from an array.
[xml]$content = get-content $file
$element = $content.PathToArray | Where-Object {$_.name -eq "ElementToRemove" }
$element.ParentNode.RemoveChild($element)
This is very simple and gets the job done.

Resources