Henry Lee
Henry Lee

Reputation: 163

why are my PowerShell results repeating?

Good day,

PowerShell rookie here...

If I output to the screen like this:

    foreach($databasePermission in $database.EnumDatabasePermissions($user.Name))
{
    Write-Host $databasePermission.PermissionState $databasePermission.PermissionType "TO" $databasePermission.Grantee
} 

I get this, which is what I want:

Grant CONNECT TO dbo

However, if I try to output to a text file like this:

    foreach($databasePermission in $database.EnumDatabasePermissions($user.Name))
{
    "$databasePermission.PermissionState $databasePermission.PermissionType TO $databasePermission.Grantee" | Out-File $filename
} 

My results repeat like this:

[dbname] Database: cust_serv, Grant, CONNECT.PermissionState [dbname] Database: cust_serv, Grant, CONNECT.PermissionType TO [dbname] Database: cust_serv, Grant, CONNECT.Grantee

Thanks!

Upvotes: 1

Views: 233

Answers (2)

manojlds
manojlds

Reputation: 301147

Good way to construct long strings is to use string formatting. It is more readable ( atleast imo, since you don't have to do $($...) etc.):

"{0} {1} TO {2}" -f $databasePermission.PermissionState,$databasePermission.PermissionType,$databasePermission.Grantee

Upvotes: 2

stej
stej

Reputation: 29449

If you access properties of an object in a string, you have to enclose it in $(...):

Look at the difference between

"$databasePermission.PermissionState"

and

"$($databasePermission.PermissionState)"

Upvotes: 3

Related Questions