Home > powershell > Powershell enters foreach loop with null object

Powershell enters foreach loop with null object

December 11Hits:1

I'm listing all backups in a given directory:

$backups = Get-ChildItem -Path $zipFilepath |  Where-Object {($_.lastwritetime -lt (Get-Date).addDays(-7)) -and  (-not $_.PSIsContainer) -and ($_.Name -like "backup*")} 

If I set it to deliberately return no files (.addDays(-600) then the following prints "Empty" (as expected):

if (!$backups) {     "Empty" } 

If I try to list the names with an empty $backups variable:

foreach ($file in $backups) {     $file.FullName; } 

I get nothing (as expected), if I change this to:

"test"+ $file.FullName; 

then I get a single "test" under the "Empty". How is this possible if $backups is empty?


This is a "feature" of Powershell. Your $backups may contain multiple $null values, as well as non-null, so Powershell must iterate the object to process the foreach. The fact the we both see $backup as a single-value scalar ($null in this case) doesn't matter, to MS at least... :)

See this Microsoft Connect Bug Report for more details -- It is "fixed" in Powershell v3.

On v2:

PS H:\> foreach ( $i in $null ) { "Hi" }

On v3:

PS H:\> foreach ( $i in $null ) { "Hi" }

(No output)


Related Articles

  • Powershell enters foreach loop with null objectDecember 11

    I'm listing all backups in a given directory: $backups = Get-ChildItem -Path $zipFilepath | Where-Object {($_.lastwritetime -lt (Get-Date).addDays(-7)) -and (-not $_.PSIsContainer) -and ($_.Name -like "backup*")} If I set it to deliberately retu

  • Foreach loop inside array/objectJanuary 26

    I don't have a good understanding of Javascript, so I don't know if I even formulated my question properly. If I have an array with objects, how do I populate and replace this 'values' with mydata values? I need some sort of foreach loop, I don't kno

  • Refactor nested foreach loop based on object propertyApril 20

    I'm using a levenshtein matching algorithm to match a title to a filename (for anime). I either use the main show title for matching or its alternative titles (flexget_titles). For that I have the following snippet of code. public function matchFilen

  • Random position of object in foreach loopAugust 13

    i need help with some "scary" thing. I'm creating some objects in foreach loop. Each object has implemented in Update function random change of position. But while i'm creating this objects in foreach loop, each object gets the same random posit

  • Bypass Approval in powershell foreach loopSeptember 21

    I have a foreach loop in powershell to delete all deleted sites that are already in recycle bin of SharePoint. But when I run this loop it asks me weather I'm sure to do this or not for every single item. How can I bypass this approval in my foreach

  • Object type not recognised on foreach loopFebruary 2

    So, i ran into a strange problem today. Let's say i have a TreeNode defined like this: TreeNode node = new TreeNode(); node.Nodes.Add(new TreeNode { Name = "aaa" }); node.Nodes.Add(new TreeNode { Name = "bbb" }); And then I call a recu

  • Object reference not set to an instance of an object. yet foreach loop is workingFebruary 17

    so im having a weird problem. when i make a linq query on a datatable I get "Object reference not set to an instance of an object." but when a use forloop on the result it works correctly.dt is a datatable var productdata = from data in dt.AsEnu

  • How can I correct my foreach loop in powershell for every Active Directory OU user?September 29

    Goal: Create a for or foreach loop to execute some code (in this case, just print x) for every user in an OU. Im using powershell 2.0, with ActiveDirectory module. So far: This is what I have (see below). It just prints out the X's for every user. Bu

  • How do I get a property value from an object in a foreach loop?January 19

    I iterate through an array(using a foreach loop) that contains two 'High Season' objects - the two objects have an id, start date and end date. I get the high season start date via getter and assign it to a variable with intentions of incrementing th

  • Trouble loading SimpleXML object for use in foreach loop : Warning: Invalid argument supplied for foreach()January 21

    I'm trying to load a simple XML object from file using simplexml_load_file(); I've been scraping around the internet trying to get a handle on an error with with the subsequent foreach loop. I'm getting an invalid foreach argument error: Warning: Inv

  • Iterating through an object of objects in a foreach loop in phpFebruary 1

    I have a function that is being passed an object that contains other objects that have permission ids in them. I need those permission ids in a foreach loop. Most of my tries give me an array to string conversion or a call to a non-object error. A fo

  • Protect foreach loop when empty listDecember 13

    Using Powershell v2.0 I want to delete any files older than X days: $backups = Get-ChildItem -Path $Backuppath | Where-Object {($_.lastwritetime -lt (Get-Date).addDays(-$DaysKeep)) -and (-not $_.PSIsContainer) -and ($_.Name -like "backup*")} for

  • How to get shortcode to work inside a foreach loop called within a shortcode?September 27

    My plugin, WP Coda Slider, uses a shortcode to get_posts and add them to the slider. If one of the posts contains shortcode the shortcode in that post will not work. $my_wpcodaslider = new wpcodaslider(); class wpcodaslider{ var $shortcode_name = 'wp

  • Is there any performance benefit in checking the item count prior to executing a foreach loop?April 9

    I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping: if (SqlParams.Count > 0) foreach (var prm in SqlParams) cmd.Parameters.Add(prm); I always prefer to do a null check instead and let

  • Refactor foreach loopsDecember 17

    I have 2 objects and I am comparing them to see which fields are equal and which are different. But I am not sure my loop is 100% correct. Does this look ok? If so, what other ways could this be coded to make it 'neater'. e.g. using LINQ I want to: l

  • wrapper class - System.NullPointerException: Attempt to de-reference a null object

    wrapper class - System.NullPointerException: Attempt to de-reference a null objectNovember 7

    I have a vf page where i am dynamically adding rows. I am using wrapper class to add empty rows evrytime. Now after clicking addrow button i am getting the following error - System.NullPointerException: Attempt to de-reference a null object External

  • Variable value not replaced in double quoted string in foreach loopJanuary 19

    I have read several threads here on SO but none of them seems to address my problem. I have even tried some of the code samples but they don't work for me. I have spent several days trying to figure this out but so far I've failed. I don't think this

  • How do I access counter in a nested foreach loop?January 20

    So, till date I have written only a handful of R codes (2 projects to be precise), which probably might justify the extent of dumbness in this question that would appear to a seasoned programmer. I am trying to parallelise my K fold cross validation

  • Is there any way to create in foreach loop?

    Is there any way to create in foreach loop?January 24

    Here is my code: var json = File.ReadAllText(@"C:\sira.json"); dynamic x = JsonConvert.DeserializeObject<dynamic>(json); Arac.adli_tip = x.adli_tip; Arac.aile_hukuku = x.aile_hukuku; Arac.avrupa_birligi_hukuku = x.avrupa_birligi_hukuku; Ar

  • Why is my FOREACH loop stopping after 3 iterations? (PHP & Stripe)

    Why is my FOREACH loop stopping after 3 iterations? (PHP & Stripe)January 26

    My code is large as I am working on a subscription PHP plugin for WordPress. However, although most is done I now face a glitch that I can't fix. This is the flow: User fills in the signup form with shipping, billing and account details I create his

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.500 s.