0

I'm pretty new when it comes to scripting with powershell (or in general whe it comes to scripting). The problem that i have, is that i got a bunch of variables i want to output in one line. Here is not the original but simplified code:

$a = 1
$b = 2
$c = $a; $b;
Write-output $c

The output looks like this:

1
2

You may guess how i want the output to look like:

12

I've searched the net to get a solution but nothing seem to work. What am i doing wrong?

1
  • "$a$b", the semi colon in Powershell means statement termination. So, since $c is a reference to $a, it prints out 1 due to the semicolon sperating the two variables of $a and $b. So, you're basically saying, print $a, then print $b. Commented Jul 13, 2021 at 15:35

2 Answers 2

6

Right now you're only assigning $a to $c and then outputting $b separately - use the @() array subexpression operator to create $c instead:

$c = @($a; $b)

Then, use the -join operator to concatenate the two values into a single string:

$c -join ''
Sign up to request clarification or add additional context in comments.

Comments

0

You can make things easier on yourself using member access or Select-Object to retrieve property values. Once the values are retrieved, you can them manipulate them.

It is not completely clear what you really need, but the following is a blueprint of how to get the desired system data from your code.

# Get Serial Number
$serial = Get-CimInstance CIM_BIOSElement | Select-Object -Expand SerialNumber

# Serial Without Last Digit
$serialMinusLast = $serial -replace '.$'

# First 7 characters of Serial Number
# Only works when serial is 7 or more characters
$serial.Substring(0,7)
# Always works
$serial -replace '(?<=^.{7}).*$'

# Get Model
$model = Get-CimInstance Win32_ComputerSystem | Select-Object -Expand Model

# Get First Character and Last 4 Characters of Model
$modelSubString = $model -replace '^(.).*(.{4})$','$1$2'

# Output <model substring - serial number substring>
"{0}-{1}" -f $modelSubString,$serialMinusLast

# Output <model - serial number>
"{0}-{1}" -f $model,$serial

Using the syntax $object | Select-Object -Expand Property will retrieve the value of Property only due to the use of -Expand or -ExpandProperty. You could opt to use member access, which uses the syntax $object.Property, to achieve the same result.

If you have an array of elements, you can use the -join operator to create a single string of those array elements.

$array = 1,2,3,'go'
# single string
$array -join ''

The string format operator -f can be used to join components into a single string. It allows you to easily add extra characters between the substrings.

Comments

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.