开发者

why are my PowerShell results repeating?

开发者 https://www.devze.com 2023-03-29 13:57 出处:网络
Good day, PowerShell rookie here... If I output to the screen like this: foreach($databasePermission in $database.EnumDatabasePermissions($user.Name))

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.开发者_StackOverflow社区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!


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)"


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
0

精彩评论

暂无评论...
验证码 换一张
取 消