0

I have a csv file:

"SamAccountName","UserPrincipalName","Telephonenumber"
"TUser","[email protected]","+15551112222"

I loop through the file:

$csvfile = Import-Csv $path
foreach ($row in $csvfile) {
    Write-Host $row.SamAccountName, "$row.SamAccountName"
}

The first $row.SamAccountName prints the sam account name string from the csv file. If I put the same variable in quotes, it prints an array. My output looks like this:

TUser @{SamAccountName=TUser; [email protected]; Telephonenumber=+15551112222}.SamAccountName

If I do .GetType() on $row.SamAccountName is says its a System.String. So why does putting it in quotes print an array?

3 Answers 3

1

When you write it like this:

"$row.SamAccountName"

only $row is recognized as part of the variable and since $row is an array that's what it outputs. If you want to write the whole thing to a string try looking into .ToString() or wrapping your original statement into a variable like this:

"$($row.SamAccountName)"

that way it will consider everything part of the variable.

Sign up to request clarification or add additional context in comments.

Comments

1

It is not printing an array, it's printing a textual interpretation of the object.

If you want to interpolate an object property in a string, you need to use the syntax "$($object.property)". So changing as below will work:

$csvfile = Import-Csv $path
foreach ($row in $csvfile) {
    Write-Host $row.SamAccountName, "$($row.SamAccountName)"
}

Or use the format string operator:

$csvfile = Import-Csv $path
foreach ($row in $csvfile) {
    "{0}" -f $row.SamAccountName
}

Comments

0

By using double quotes around the "$row.SamAccountName" you are telling PowerShell to get print the row IE the array of objects from that row. As we can see from your output:

TUser @{SamAccountName=TUser; [email protected]; Telephonenumber=+15551112222}.SamAccountName

This is your Write-Host Statement. First, you are writing $row.SamAccountName and second you are adding the whole Row object ie the Array. The .SamAccountName in the double quotes is taken as a literal string, therefore, it is not accessing the row to retrieve its value.

If you just put $row in double quotes you will get this:

@{SamAccountName=TUser; [email protected]; Telephonenumber=+15551112222}

If you want to use double quotes around a variable use this if you are trying to access a sub expression.

"$($row.SamAccountName)"

This is the subExpression form.

The link below is to help learn about escape characters and string concatenation. https://ss64.com/ps/syntax-esc.html

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.