How can I increment the index of an array that is in quotes? - powershell

I can get the individual lines of a text file in powershell by indexing surround them with quotes by sub-expression
$textFile = Get-Content "myText.txt"
$i = 0
"$($textFile[$i])"
This will output the first line from the test file. But when I try to increment the index, it's not being passed to the variable when I call it, and still outputs the first line.
$i++ # value is now 1
"$($textFile[$i])" # value is still at the first index
$i++ # value is now 2
"$($textFile[$i])" # value is still at the first index
$i++ # value is now 3
"$($textFile[$i])" # value is still at the first index
The reason I'm keeping the variable in quotes is because that one line of the text file part of a bigger string that I can execute
while ($i -lt $textFile.count)
{
$remote = "Enter-PSSession -ComputerName`", $(textFile[$i])"
Invoke-Expression $remote
$global:i++
}
Thanks

I Was able to produce the desired outcome by using a foreach loop instead of a while loop:
foreach ($line in $textFile)
{
$remote = "Enter-PSSession -ComputerName`" $line"
Invoke-Expression $remote
}

Related

Add Content to a specific line in powershell

I have seen this post:
Add-Content - append to specific line
But I cannot add these lines because "Array index is out of range".
What my script is doing:
Find the line
Loop through the array that contains the data i want to add
$file[$line]+=$data
$line+=1
Write to file
Should I create a new file content and then add each line of the original file to it?
IF so, do you know how to do that and how to stop and add my data in between?
Here is the part of my code where I try to add:
$f=Get-Content $path
$ct=$begin+1 #$begin is the line where I want to place content under
foreach($add in $add_to_yaml)
{
$f[$ct]+=$add
$ct+=1
}
$f | Out-File -FilePath $file
Let's break down your script and try to analyze what's going on:
$f = Get-Content $path
Get-Content, by default, reads text files and spits out 1 string per individual line in the file. If the file found at $path has 10 lines, the resulting value stored in $f will be an array of 10 string values.
Worth noting is that array indices in PowerShell (and .NET in general) are zero-based - to get the 10th line from the file, we'd reference index 9 in the array ($f[9]).
That means that if you want to concatenate stuff to the end of (or "under") line 10, you need to specify index 9. For this reason, you'll want to change the following line:
$ct = $begin + 1 #$begin is the line where i want to place content under
to
$ct = $begin
Now that we have the correct starting offset, let's look at the loop:
foreach($add in $add_to_yaml)
{
$f[$ct] += $add
$ct += 1
}
Assuming $add_to_yaml contains multiple strings, the loop body will execute more than once. Let's take a look at the first statement:
$f[$ct] += $add
We know that $f[$ct] resolves to a string - and strings have the += operator overloaded to mean "string concatenation". That means that the string value stored in $f[$ct] will be modified (eg. the string will become longer), but the array $f itself does not change its size - it still contains the same number of strings, just one of them is a little longer.
Which brings us to the crux of your issue, this line right here:
$ct += 1
By incrementing the index counter, you effectively "skip" to the next string for every value in $add_to_yaml - so if the number of elements you want to add exceeds the number of lines after $begin, you naturally reach a point "beyond the bounds" of the array before you're finished.
Instead of incrementing $ct, make sure you concatenate your new string values with a newline sequence:
$f[$ct] = $f[$ct],$add -join [Environment]::Newline
Putting it all back together, you end up with something like this (notice we can discard $ct completely, since its value is constant an equal to $begin anyway):
$f = Get-Content $path
foreach($add in $add_to_yaml)
{
$f[$begin] = $f[$begin],$add -join [Environment]::Newline
}
But wait a minute - all the strings in $add_to_yaml are simply going to be joined by newlines - we can do that in a single -join operation and get rid of the loop too!
$f = Get-Content $path
$f[$begin] = #($f[$begin];$add_to_yaml) -join [Environment]::Newline
$f | Out-File -FilePath $file
Much simpler :)

ArrayList not returning expected result

Why does this code not work?
$method = {
[System.Collections.ArrayList]$array;
for ($i=0; $i -le 50; $i++) { $array += $i }
}
Executing the scriptblock with:
&$method
Shows on the console:
1, 2, 3, 4, 5, 6
when it should print 50 numbers?
The Add() method of the ArrayList type emits the index at which a new item was inserted. Cast the expression to [void], pipe it to Out-Null or assign it to $null to supress this output:
[void]$array.Add($i)
# or
$array.Add($i) |Out-Null
# or
$null = $array.Add($i)
Avoid piping to Out-Null if you do this many times, casting or assigning is much faster than piping.
The code you posted shouldn't generate any output at all, unless you already have a variable $array defined in the parent scope. The statement
[System.Collections.ArrayList]$array
casts the value of the variable $array to the type ArrayList and echoes it. If the variable has a value in the parent scope the statement will output the value as an array list, otherwise the output will be null. The subsequent loop will not use that variable, but instead increment a new (local) variable $array. You can verify that by placing a statement $array.GetType().FullName at the end of the scriptblock. You'll get System.Int32, not System.Collections.ArrayList (or System.Object[]) as you might expect.
If you want to instantiate an ArrayList object, add numbers to it, and output that list at the end of the scriptblock, you need to change your code to something like this:
$method = {
[Collections.ArrayList]$array = #()
for ($i=0; $i -le 50; $i++) { $array += $i }
$array
}
Note the assignment operation in the first statement.
Demonstration:
PS C:\> $sb = { [Collections.ArrayList]$a; 0..50 | % { $a += $_ }; $a.GetType().FullName; $a }
PS C:\> &$sb
System.Int32
1275
PS C:\> $sb = { [Collections.ArrayList]$a = #(); 0..50 | % { $a += $_ }; $a.GetType().FullName; $a }
PS C:\> &$sb
System.Collections.ArrayList
0
1
...
49
50

How to declare and get array value

I am new to Powershell, first time using it.
I have declared an array and use array value but using below code, I am not able to retrieve the array value...Any idea what I am missing here?
Just FYI.. I am executing script in ADOBE ILLUSTRATOR and for testing I am using 3 here in condition (for loop)... will use $array later
$array = "a.jpg","b.jpg","c.jpg";
for ($i=1; $i-le=3; $i++)
{
$.writeln("This is line number " + $array[$i]);
var targetFileName = $array[$i]+'.png';
$.writeln(targetFileName);
}
I tried $array[$i].toString() as well but still not getting values... I am getting 0
Any help is appreciated and thanks in advance to all for your help
for ($i=1; $i-le=3; $i++)
The condition in the above line doesn't have a valid comparison operator. Change that to
for ($i=1; $i -le 3; $i++)
if you want the loop to terminate after 3 cycles.
$.writeln("This is line number " + $array[$i]);
var targetFileName = $array[$i]+'.png';
$.writeln(targetFileName);
This is not valid PowerShell. Looks more like JavaScript to me. In PowerShell it should probably look like this:
Write-Output "This is line number $i"
$targetFileName = $array[$i] + '.png'
Write-Output $targetFileName
or shorter
"This is line number $i"
$array[$i] + '.png'
Note that PowerShell arrays are zero-based, so the last iteration ($array[3]) will return $null instead of an element from the array. If you want to iterate over the elements of the array you should change your loop to this:
for ($i=0; $i -lt $array.Length; $i++) {
"This is line number $($i+1)"
$array[$i] + '.png'
}
or (better) pipe your array into a foreach loop:
$i = 0
$array | % {
"This is line number " + ++$i
$_ + '.png'
}

Powershell - Remove space between two variables

I have two array's which contain a selection of strings with information taken from a text file. I then use a For Loop to loop through both arrays and print out the strings together, which happen to create a folder destination and file name.
Get-Content .\PostBackupCheck-TextFile.txt | ForEach-Object { $a = $_ -split ' ' ; $locationArray += "$($a[0]):\$($a[1])\" ; $imageArray += "$($a[2])_$($a[3])_VOL_b00$($a[4])_i000.spi" }
The above takes a text file, splits it into separate parts, stores some into the locationArray and other information in the imageArray, like this:
locationArray[0] would be L:\Place\
imageArray[0] would be SERVERNAME_C_VOL_b001_i005.spi
Then I run a For Loop:
for ($i=0; $i -le $imageArray.Length - 1; $i++)
{Write-Host $locationArray[$i]$imageArray[$i]}
But it places a space between the L:\Place\ and the SERVERNAME_C_VOL_b001_i005.spi
So it becomes: L:\Place\ SERVERNAME_C_VOL_b001_i005.spi
Instead, it should be: L:\Place\SERVERNAME_C_VOL_b001_i005.spi
How can I fix it?
Option #1 - for best readability:
{Write-Host ("{0}{1}" -f $locationArray[$i], $imageArray[$i]) }
Option #2 - slightly confusing, less readable:
{Write-Host "$($locationArray[$i])$($imageArray[$i])" }
Option #3 - more readable than #2, but more lines:
{
$location = $locationArray[$i];
$image = $imageArray[$i];
Write-Host "$location$image";
}

Error with Substring Code - Powershell

I'm getting errors with the code below. I'm trying to take lines in a text file that are over 180 characters and parse them to a new line. I have to take the first 22 characters and put it in from of part two since it contains inital data that's needed on the line:
$data = get-content "C:\TestFile.txt"
$strAcct= #()
$strPart1= #()
$strPart2= #()
$strLength= #()
foreach($line in $data)
{
if ( $line.length -gt 181)
{ $strLength = $line.length
$strAcct += $line.substring(0,22)
$strPart1 += $line.substring(0,180)
$strPart2 += $line.substring(181,$strLength)
Add-Content "C:\TestFile-Output.txt" $strPart1
Add-Content "C:\TestFile-Output.txt" $strAcct $strPart2
}
Else {
Add-Content "C:\TestFile-Output.txt" $line
}
}
Substring takes an index, and the number of characters to take starting from that index. Your third substring bombs, because you are trying to take more characters than there are in the string. Change it to $strLength - 181, or alternatively, you can leave the second parameter out entirely, to just take the rest of the string starting from the index in the first parameter.
Change this:
$line.substring(181, $strLength)
to this:
$line.substring(181)
or even this:
$line.substring(181, $strLength - 181)