powershell - variable replaced during loop.

Answered powershell - variable replaced during loop.

  • Tuesday, May 01, 2012 2:39 PM
     
      Has Code

    (this is from an issue that, once resolved, has become an education opportunity)

    I have a directory with text files that I need to read the first two lines of data in each. What I looking for, output-wise is:

     filename
     line 1
     line 2
     filename
     line 1
     line 2

    When i attempt to run this script, the directory is parsed and filenames read into memory but the directory itself is replace with cwd. so "z:\blah\foo.txt" becomes "c:\users\user.domain\documents\foo.txt"

    here is my code thus far:

    $path = $Argument1
    
    Get-ChildItem $path | foreach-Object{
    	Get-ItemProperty $_.name
    	(Get-Content $_)[0 .. 1]
    }

    I am assuming this is because the "Get-ChildItem" only produces the name of the object here and not where it is located? I am a powershell neophyte here so I am looking for some direction. Is this better done with a for/each loop and plug in the directory?

    Eventually, my desire is to have this output to csv or something for consumption by others but one thing at a time, right?

All Replies

  • Tuesday, May 01, 2012 2:57 PM
     
     Answered

    Get-Childitem returns the full path name of the file.  Your second example should produce the results you need, except you don't need to use Get-ItemProperty.  Just replace that line with:

    Write-Host $_.fullname


    Grant Ward, a.k.a. Bigteddy

    What's new in Powershell 3.0 (Technet Wiki)

    • Marked As Answer by PONA-Boy Tuesday, May 01, 2012 3:58 PM
    •  
  • Tuesday, May 01, 2012 3:01 PM
    Moderator
     
      Has Code

    Try

    Get-ItemProperty $_.VersionInfo.FileName


    Richard Mueller - MVP Directory Services

  • Tuesday, May 01, 2012 3:14 PM
     
     

    Thanks Bigteddy.

    Actually, this went a long way towards answering the question why the loop wasn't looking in the right place for the Get-Content cmdlet...if i replace $_ with $_.fullname, the script runs as advertised. My guess here is that, within Foreach-Object, $_ only expands to "foo.txt" and the shell interprets that as looking in cwd. When I use $_.fullname, it expands to "z:\blah\foo.txt".

    Interesting.

  • Tuesday, May 01, 2012 3:19 PM
    Moderator
     
     

    The $_ variable represents the current object in a ForEach-Object loop. If you just output $_, PowerShell's default output formatter decides what to output. Since you want to control what gets output, specify the object property (or properties) you want to output. In your case, $_.FullName returns a [String] object representing the full path and filename of the file.

    Bill