为什么我的PowerShell结果重复?

时间:2011-08-19 15:57:30

标签: powershell

美好的一天,

PowerShell新秀......

如果我像这样输出到屏幕:

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

我得到了这个,这就是我想要的:

Grant CONNECT TO dbo

但是,如果我尝试输出这样的文本文件:

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

我的结果重复如下:

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

谢谢!

2 个答案:

答案 0 :(得分:3)

如果您访问字符串中对象的属性,则必须将其括在$(...)中:

看看

之间的区别
"$databasePermission.PermissionState"

"$($databasePermission.PermissionState)"

答案 1 :(得分:2)

构造长字符串的好方法是使用字符串格式。它更具可读性(至少imo,因为你不必做$($...)等)。

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