Powershell如何将脚本修改为硬编码“| export-csv c:\ temp \ filename.csv -notypeinformation“

问题描述 投票:1回答:1

我有这个非常棒的脚本,用于生成一个文件夹列表及其分配的安全组和每个组中的每个用户。

当我运行它时,我输入.\getfolderacls.ps1 -verbose | export-csv c:\temp\filename.csv -notypeinformation

这完全有效,但我想硬编码| export-csv...部分,以便我可以在没有参数的情况下运行它(或者它们是参数?)。

我尝试简单地将| export-csv c:\temp\test.csv -notypeinformation附加到脚本的底部,但是会抛出错误An empty pipe element is not allowed

脚本:

    [CmdletBinding()]
Param (
    [ValidateScript({Test-Path $_ -PathType Container})]
    [Parameter(Mandatory=$false)]
    [string]$Path       
)
Write-Verbose "$(Get-Date): Script begins!"
Write-Verbose "Getting domain name..."
$Domain = (Get-ADDomain).NetBIOSName

Write-Verbose "Getting ACLs for folder $Path"

Write-Verbose "...and all sub-folders"
Write-Verbose "Gathering all folder names, this could take a long time on bigger folder trees..."
$Folders = Get-ChildItem -Path I:\foldername -Directory -Recurse -Depth 2

Write-Verbose "Gathering ACL's for $($Folders.Count) folders..."
ForEach ($Folder in $Folders)
{   Write-Verbose "Working on $($Folder.FullName)..."
    $ACLs = Get-Acl $Folder.FullName | ForEach-Object { $_.Access | where{$_.IdentityReference -ne "BUILTIN\Administrators" -and $_.IdentityReference -ne "BUILTIN\Users"  }}
    ForEach ($ACL in $ACLs)
    {   If ($ACL.IdentityReference -match "\\")
        {   If ($ACL.IdentityReference.Value.Split("\")[0].ToUpper() -eq $Domain.ToUpper())
            {   $Name = $ACL.IdentityReference.Value.Split("\")[1]
                If ((Get-ADObject -Filter 'SamAccountName -eq $Name').ObjectClass -eq "group")
                {   ForEach ($User in (Get-ADGroupMember $Name -Recursive | Select -ExpandProperty Name))
                    {   $Result = New-Object PSObject -Property @{
                            Path = $Folder.Fullname
                            Group = $Name
                            User = $User
                            FileSystemRights = $ACL.FileSystemRights
                                                                               }
                        $Result | Select Path,Group,User,FileSystemRights
                    }
                }
                Else
                {    $Result = New-Object PSObject -Property @{
                        Path = $Folder.Fullname
                        Group = ""
                        User = Get-ADUser $Name | Select -ExpandProperty Name
                        FileSystemRights = $ACL.FileSystemRights
                                            }
                    $Result | Select Path,Group,User,FileSystemRights
                }
            }
            Else
            {   $Result = New-Object PSObject -Property @{
                    Path = $Folder.Fullname
                    Group = ""
                    User = $ACL.IdentityReference.Value
                    FileSystemRights = $ACL.FileSystemRights
                                    }
                $Result | Select Path,Group,User,FileSystemRights
            }
        }
    }
}
Write-Verbose "$(Get-Date): Script completed!"
powershell syntax scriptblock
1个回答
0
投票

你的脚本的输出是在foreach循环中生成的 - ForEach ($Folder in $Folders) ...(而不是通过ForEach-Object cmdlet,不幸的是,它也是foreach的别名)。

为了将foreach循环的输出发送到管道,您可以将其包装在脚本块({ ... })中并使用点源运算符(.)调用它。或者,使用调用运算符(&),在这种情况下,循环在子范围中运行。

以下是简化示例:

# FAILS, because you can't use a foreach *loop* directly in a pipeline.
PS> foreach ($i in 1..2) { "[$i]" } | Write-Output
# ...
An empty pipe element is not allowed. 
# ...


# OK - wrap the loop in a script block and invoke it with .
PS> . { foreach ($i in 1..2) { "[$i]" } } | Write-Output
[1]
[2]

注意:我使用Write-Output作为您可以管道的cmdlet的示例,仅用于本演示的目的。在你的情况下需要的是将你的foreach循环包裹在. { ... }中,并用| Export-Csv ...代替Write-Output

使用. { ... }& { ... }将循环内生成的输出一个接一个地发送到管道 - 因为(通常)由cmdlet生成的输出发生。


另一种方法是使用$(...),子表达式运算符(或@(...),数组子表达式运算符,在这种情况下的工作方式相同),在这种情况下,循环输出在发送之前作为整体收集在内存中通过管道 - 这通常更快,但需要更多的内存:

# OK - call via $(...), with output collected up front.
PS> $(foreach ($i in 1..2) { "[$i]" }) | Write-Output
[1]
[2]

要在代码的上下文中拼出. { ... }解决方案 - 添加的行标有# !!!注释(还要注意根据Lee_Dailey对问题的评论来改进代码的可能性):

[CmdletBinding()]
Param (
    [ValidateScript({Test-Path $_ -PathType Container})]
    [Parameter(Mandatory=$false)]
    [string]$Path       
)
Write-Verbose "$(Get-Date): Script begins!"
Write-Verbose "Getting domain name..."
$Domain = (Get-ADDomain).NetBIOSName

Write-Verbose "Getting ACLs for folder $Path"

Write-Verbose "...and all sub-folders"
Write-Verbose "Gathering all folder names, this could take a long time on bigger folder trees..."
$Folders = Get-ChildItem -Path I:\foldername -Directory -Recurse -Depth 2

Write-Verbose "Gathering ACL's for $($Folders.Count) folders..."
. { # !!!
  ForEach ($Folder in $Folders) 
  {   Write-Verbose "Working on $($Folder.FullName)..."
      $ACLs = Get-Acl $Folder.FullName | ForEach-Object { $_.Access | where{$_.IdentityReference -ne "BUILTIN\Administrators" -and $_.IdentityReference -ne "BUILTIN\Users"  }}
      ForEach ($ACL in $ACLs)
      {   If ($ACL.IdentityReference -match "\\")
          {   If ($ACL.IdentityReference.Value.Split("\")[0].ToUpper() -eq $Domain.ToUpper())
              {   $Name = $ACL.IdentityReference.Value.Split("\")[1]
                  If ((Get-ADObject -Filter 'SamAccountName -eq $Name').ObjectClass -eq "group")
                  {   ForEach ($User in (Get-ADGroupMember $Name -Recursive | Select -ExpandProperty Name))
                      {   $Result = New-Object PSObject -Property @{
                              Path = $Folder.Fullname
                              Group = $Name
                              User = $User
                              FileSystemRights = $ACL.FileSystemRights
                                                                                }
                          $Result | Select Path,Group,User,FileSystemRights
                      }
                  }
                  Else
                  {    $Result = New-Object PSObject -Property @{
                          Path = $Folder.Fullname
                          Group = ""
                          User = Get-ADUser $Name | Select -ExpandProperty Name
                          FileSystemRights = $ACL.FileSystemRights
                                              }
                      $Result | Select Path,Group,User,FileSystemRights
                  }
              }
              Else
              {   $Result = New-Object PSObject -Property @{
                      Path = $Folder.Fullname
                      Group = ""
                      User = $ACL.IdentityReference.Value
                      FileSystemRights = $ACL.FileSystemRights
                                      }
                  $Result | Select Path,Group,User,FileSystemRights
              }
          }
      }
  }
} | Export-Csv c:\temp\test.csv -notypeinformation  # !!!
Write-Verbose "$(Get-Date): Script completed!"
© www.soinside.com 2019 - 2024. All rights reserved.