0

Using PowerShell, I created a script that other people will be using. Because of this, I am refactoring my code to use more variables. I have a variable named $endcol that will always be equal to the last string placed in another variable, $columnsToExtract. How can I make this work?

Right now my code is:

$columnsToExtract = '30', '31', '39'
$endcol = 39
5
  • 2
    You're kidding, don't you? ;-) $columnsToExtract[-1] Commented Mar 23, 2018 at 19:20
  • Wow... Too easy. Commented Mar 23, 2018 at 19:25
  • Very idiomatic: $columnsToExtract | Select-Object -Last 1 Commented Mar 23, 2018 at 21:55
  • @beatcracker: The pipeline is an elegant tool, but not always the right one, especially when it comes to performance: compare Measure-Command { 1..1e6 | Select-Object -Last 1 } to Measure-Command { (1..1e6)[-1] } Commented Mar 24, 2018 at 3:09
  • 1
    @mklement0 Yep, that's why it's a comment, not an answer. Should've mention performance issues, though. Commented Mar 24, 2018 at 11:20

2 Answers 2

1

To get always the last element of an array you can use the "negativ index" starting with -1. Like this:

$columnsToExtract = '30', '31', '39'
$endcol = $columnsToExtract[-1]
Sign up to request clarification or add additional context in comments.

Comments

-1
$columntoextract = '30','31','39'
$endcol = $($columntoextract[2])
$endcol

1 Comment

What is when the array has less or more than 3 elements? ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.