Jump to content
Ghost1982

How to display line numbers of input file

Recommended Posts

Posted (edited)

Hello

 

Is there any way how I can display line numbers of an input file.

Let's say i've got list of AD groups to create (i.e. 1000 of them) in some input file. What I would like to do is to display in the console screen current line that is being processed. Thanks to that I know how far the script is :)

For now, what I'm doing is that

$content = Get-Content input.txt
Foreach ($ADgrp in $content ) {
     Write-host Creating AD group: $ADgrp
     New-AdGroup -Name "$ADgrp" -SamAccountName $ADgrp
etc.
     Start-Sleep 3
}

So in the console window I wil lreceive:

Creating AD group: <some group name>

But I would like to have something like this:

Processing 1 of 1000 lines
Creating AD group: <some group name>

Processing 2 of 1000 lines
Creating AD group: <some group name>

etc.

 

How can I add the "counter" within Foreach loop?

 

 

Edited by Ghost1982

Share this post


Link to post
Share on other sites

There are a couple ways to skin the proverbial cat, but here is a simple method that will work with any size collection:

$content = Get-Content <filepath.txt>

foreach ($line in $content) {
    Write-Host "Processing line $($content.IndexOf($line) + 1) out of $($content.Count)"
}

Notice the +1, as $content.IndexOf($line) will begin counting at 0. Post back if you have any questions.


"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Share this post


Link to post
Share on other sites
Posted (edited)

Meanwhile I did something like this:

$content = Get-Content input.txt
$lines = Get-content input.txt | Measure-Object -Line | Select-Object -ExpandProperty Lines
Foreach ($line in $content | Out-String -Stream | Select-String '.*' | Select-Object -Property LineNumber,Line)
{
    $number = $line | Select-Object -ExpandProperty LineNumber
    $ADgrp = $line | Select-Object -ExpandProperty Line
    Write-Host "Line" $number "of" $lines
    New-AdGroup -Name "$ADgrp" -SamAccountName $ADgrp
    Start-Sleep 2
}

 

 

Edited by Ghost1982

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...