5

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?

1 Answer 1

4

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";
}
Sign up to request clarification or add additional context in comments.

8 Comments

This works perfectly ! I'm fairly new to Powershell though, what exactly does that do?
@TheD: -f is a Powershell way to do String.Format. You can put some static text in between {0} and {1} and it's very readable. Option #2 is to escape your variables, for this you need many dollar signs, and it's harder to read and comprehend.
@TheD: no problem, also check option #3 I just added. :)
I'd consider Option 2 to be more readable than Option 1, personally, but I always find the -f format operator ridiculously non-intuitive. There ought to be a command Format-String or something. It's aberrant enough to be distasteful to me.
@BaconBits I'm never been frustrated... I'm a lucky sysadmin with a good .net background :). But yes -f is hard to find in help and in google too. Anyway for future comments's readers you can read about -f doing get-help about_Operators.
|

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.