Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 660 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Powershell script indentation for long strings

#1
This problem does not have to be solved this way, but it would save me a lot of precious time if it can be:

I have been logging "line at a time" to a log file. Like this:


$mylogentry = "A string of text containing information"
$mylogentry | out-file -append $log_file_path
$array_of_log_entries += $mylogentry

The reason for the array is that I join them into a Send-Message body.

When I have long quotes however, I like to break them across lines. I can do this using the backtick '`' character.
What I have never worked out is how to escape tabs if the quote line is nested under something else. Using backtick before each indentation doesn't remove the tab.

If you look at sites like this:

[To see links please register here]

you'll see that even while he is encouraging indentation, his code is not indented for the parameters. (You can actually tab those in because whitespace is ignored outside of quotes. Maybe he was just making a point)

This is an attempted example at what I mean. (Note Im having trouble replicating the formatting on SE. 4 space indent doesn't seem to create a code block anymore)


if($somecondition){
$mylogentry = "A string of really long text for non-technical people `
` ` continue to write text here. Additional info (technical): $techvar"

That string would have a big gap between 'people' and 'continue' due to my indenting. I can of course have 'continue' begin at column 0 but then my code looks even more stupid.
Reply

#2
<!-- language-all: lang-powershell -->

You can't escape away the tabs or spaces you inserted into the string; they're inside the quotes and part of the string now (and so are the line breaks for that matter).

## You have a few options:

1. Don't break the string at all; let it ride. Obviously not what you want to do, but it works.
2. Use @Matt's suggestion and concatenate the strings. As long as the quotes begin *after* the indentation, you'll be fine.
3. Don't indent the next lines. This assumes you do want the line breaks as part of the string. It can look messy, but it will be a) readable without scrolling and b) functional. It looks something like this:

if ($fakeCondition) {
if ($fauxCondition) {
$longString = "Hello this string is too long
to be just one big line so we'll break it up into
some smaller lines for the sake of readability."
# Code that uses the string
Write-Host $longString
}
}

4. Other stuff: use an array with one element for each line and then join it, or use .NET's `StringBuilder`, but those are overkill to solve what is essentially a formatting annoyance for you.

Here strings (using `@"` to begin a string and `"@` to end it) will have the same problem as option 3 (the lines cannot be indented or the tabs/spaces will be embedded in the string).

## My View
When I run into this issue of long strings polluting the code, I usually start to rethink embedding the strings, or where I'm embedding them.

I might break this functionality into a function, then accept the string as a parameter (pushing the problem off to a different part of the code, but it can be helpful).

Sometimes I'll put it into a here document or long string at the top of the script and then use the variable later on.

Sometimes it means saving these strings in a separate file and reading the contents at run time.

All depends on the situation.
Reply

#3
Would you consider using string concatenation instead?

$test = "I would like to think that his is an example of a long string. Grammar aside I mean long as" +
" in super long. So long even that I have to use lots of letters to get my message" +
" across"

Which would output the following:

I would like to think that his is an example of a long string. Grammar aside I mean long as in super long. So long even that I have to use lots of letters to get my message across

Since you are joining strings with the `+` it would effectively ignore the white space between the quoted strings.

---

You could store the string as a newline delimited string and use a little regex to clean it up after the fact. It has limited use cases but if you are doing this a lot and [braintists answer][1] is not helping ....

$test = "I would like to think that his is an example of a long string. Grammar aside I mean long as
in super long. So long even that I have to use lots of letters to get my message
across" -replace "(?m)^\s+" -replace "`r`n"," "

So it is typed as a single string. First replace removes all leading whitespace. The second changes all of the newline into space. Both work to make it into a single ling again.

[1]:

[To see links please register here]

Reply

#4
I'd like to share some options in addition to other answers.

# Joining array of substrings (explicit)

Unary `-join` operator

``` powershell
$singleLineText = -join @(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim "
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea "
"commodo consequat."
)
```

Binary `-join` operator

``` powershell
$singleLineText = @(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod"
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim"
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea"
"commodo consequat."
) -join ' '
```

**Pros:**

+ No plus signs (+) or commas (,) needed.
+ Easy switch to binary ``-join "`r`n"`` operator for multiline string.
+ Free to use desired indentations.

**Cons:**

- Text manipulations can be tiresome.

# Joining array of substrings (implicit) | avoid

Appending to an empty string.

``` powershell
$singleLineText = '' + @(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod"
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,"
"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo"
"consequat."
)
```

Piping to script block and using `$input` - an automatic variable.

``` powershell
$singleLineText = @(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod"
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,"
"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo"
"consequat."
) | & { "$input" }
```

Whenever an array is coerced into a string, `[System.String]::Join(separator, array)` method is applied implicitly. Where the separator is " " (space) by default, and can be overwritten by setting `$OFS` - the Ouptut Field Sperator special variable.

**Pros:**

+ Suited for joining pipe output.

**Cons:**

- Lack of clarity (for several reasons), thus should be avoided whenever possible.

# Here-string

``` powershell
$singleLineText = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
"@ -replace "`r" -replace "`n", ' '
```

**Pros:**

+ Good for drop-in big sheets of arbitrary preformatted text (like source code).
+ Preserves source indentations.
+ No need to escape quotes.

**Cons:**

- Not friendly to script formatting.
- Can be hard to keep track of trailing white-spaces.

# The addition assignment operator (`+=`)

``` powershell
$s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ";
$s += "eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad ";
$s += "minim veniam, quis nostrud exercitation ullamco laboris nisi ut ";
$s += "aliquip ex ea commodo consequat.";
```

**Pros:**

+ Most obvious, universal and well-known syntax (outside of PowerShell).
+ Mostly programming language agnostic *.

*\* Variable naming conventions may be violated in some programming languages.*

**Cons:**

- Text manipulations can be tiresome.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through