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'
}
Related
I would like to be able to add functionality to a PowerShell script to move one spot forwards or one spot backwards when in a foreach loop. While looping through a foreach statement, is it possible to move forwards and backwards or to identify what point in the array the current item lies?
Edit - the items in the array are files, not numbers
Yes - it's called a for loop!
For data structures that we can index into (arrays, lists, etc.), the foreach loop statement can easily be translated to a for loop statement, like so:
# This foreach loop statement
foreach($item in $array){
Do-Something $item
}
# ... is functionally identical to this for loop statement
for($i = 0; $i -gt $array.Length; $i++){
$item = $array[$i]
Do-Something $item
}
Since we have direct access to the current index (via $i) in the for loop, we can now use that as an offset to "look around" that position in the array:
$array = #(1,2,3,4)
for($i = 0; $i -lt $array.Length;$i++)
{
$item = $array[$i]
if($i -gt 0){
# If our index position $i is greater than zero,
# then there must be _at least_ 1 item "behind" us
$behind = $array[$i - 1]
}
if($i -lt ($array.Length - 1)){
# Not at end of array, we can also "look ahead"
$ahead = $array[$i + 1]
}
}
Be careful about checking that you don't use an $i value greater than $array.Length (which would result in $null) or less than 0 (in which case PowerShell will start reading the array backwards!)
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
}
Introduction to question
I'm trying to search for the following values: '02-08-1997' and '01-08-1997' in string $b1. To find that value, I used searching for the starting and ending index of the values around it.
How did I do it?
To do this I used 4 For loops, only to execute the exact same thing over and over again. I know this can be done much simpler; so far I haven't found a way to do so yet. I have to write multiple scripts like this, so I really need to find a simpler - more easy to read - way to do so.
These are 2 of the For loops I'm using:
$b1 = 'set-aduser -identity 3423-234-23-42-432 dorstm -replace #{ geboortedatum = 01-08-1997 } waarde_org = 02-08-1997'
For ($i = 0; $i -lt $b1InArray.Length; $i++) {
if ($b1InArray[$i].contains("=")) {
$e = $i
break
}
}
For ($j = ($e + 1); $j -lt $b1InArray.Length; $j++) {
if ($b1InArray[$j].contains("}")) {
$f = $j
break
}
}
Looks like you're trying to use more of a Java solution. In Powershell you can use 'ForEach'
$b1 = 'set-aduser -identity 3423-234-23-42-432 dorstm -replace #{ geboortedatum = 01-08-1997 } waarde_org = 02-08-1997'
foreach ($b in $b1) {
if ( $b -contains '=') {
$f = $j
}
}
Note: $b in the foreach loop condition can be anything you want it to be just like $i in Java.
If you want to get the index of the strings you are searching for: there's a method for that:
$b1.IndexOf('02-08-1997')
$b1.IndexOf('01-08-1997')
No need to write loops. For simple things like this .Net has a working method for you.
Many ways to do this. This could work for you:
(Select-String -InputObject $b1 -allmatches -Pattern '\d{2}-\d{2}-\d{4}').matches.value
it will output all dates from your $b1 string as an array of strings. Assuming all dates have the same format like your example.
Fiddle with regex at https://regex101.com/
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";
}
I am trying to find out why the following occurs if you have
$arr = #("Filename1", "Filename2")
for($i =0; $i -le $arr.Length -1; $i++) {
write-host ".\"$arr[$i]
write-host ".\$arr[$i]"
write-host $arr[$i]
}
So taking just one loop through it produces:
".\ Filename1"
".\ Filename1 Filename2[0]"
"Filename1"
Just referencing the array[index] will produce the correct value, but if I concatenated with a string it places a space between the string and value. When placed within the string I assume it is dumping the entire contents because it is evaluating $array then evaluating $i ending up with
".\ filename1 filename2[index number]"
But if I assign the individual value to a separate variable and concatenate it with a string there is no space? Why is that:
Example:
$name = $arr[$i]
write-host ".\$name"
output = ".\filename1"
which is correct.
You have to do:
write-host ".\$($arr[$i])"
so that it is evaluated as array indexing.
It would be the case with something like accessing properties of an object or key of hash etc within the string:
PS > $a = #{test="A";test2="B"}
PS > write-host "$a.test"
System.Collections.Hashtable.test
PS > write-host "$($a.test)"
A
Another alternative is to use string formatting, especially useful when you have lots of variables / objects in the string:
write-host (".\{0}" -f $arr[$i])
Your code should look like this:
$arr = #("Filename1", "Filename2")
#for($i =0; $i -le $arr.Length-1; $i++) {
for($i =0; $i -le $arr.Length; $i++) {
write-host ".\"$arr[$i]
#write-host ".\$arr[$i]"
write-host ".\$($arr[$i])"
write-host $arr[$i]
}