【问题标题】:Powershell - importing data from filePowershell - 从文件中导入数据
【发布时间】:2015-10-04 09:37:16
【问题描述】:

我是 Powershell 新手,但遇到了问题。我在下面有这段代码,执行后它会提示在 AD 中输入组名,然后将该组的所有成员导出到 .csv 文件中。如何更改此项以从 .csv 文件导入多个组名?

param
(   
    [Parameter(Mandatory=$true,position=0)]
    [String]$GroupName
)

$GFile = New-Item -type file -force "C:\Scripts\GroupDetails.csv"

$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name

ForEach ($Group in $Groups) {

    Get-ADGroupMember -identity $($group.name) -recursive | Select-Object samaccountname | Out-File $GFile -append
}

【问题讨论】:

    标签: powershell csv import


    【解决方案1】:

    也许这样的事情会帮助你:

    Param (
        [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
        [String]$ImportFile = 'S:\Test\Input_Test\GroupNames.txt',
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [String]$SaveFolder = 'S:\Test\Input_Test'
    )
    
    $Groups = Get-Content $ImportFile
    
    ForEach ($Group in $Groups) {
        Get-ADGroupMember -Identity $Group -Recursive | 
            Select-Object -ExpandProperty SamAccountName | 
                Out-File -LiteralPath (Join-Path $SaveFolder "$Group.txt")
    }
    

    你可以用你想要的组填充文件GroupNames.txt,它会为每个组创建一个文件。

    内容 GroupNames.txt:

    Group 1
    Group 2
    

    如果你想更高级一点,你可以创建一个这样的函数:

    Function Export-ADGroupMembersToFile {
        Param (
            [Parameter(Mandatory)]
            [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
            [String]$ImportFile,
            [Parameter(Mandatory)]
            [ValidateScript({Test-Path -Path $_ -PathType Container})]
            [String]$SaveFolder
        )
    
        $Groups = Get-Content $ImportFile
    
        $OutFile = Join-Path $SaveFolder "Groups_$(Get-Date -F 'yyyyMMddHHmm').txt"
        Write-Verbose  "Output will be saved to file '$OutFile'"
    
        ForEach ($Group in $Groups) {
            Write-Verbose "GroupName: $Group"
            "`n", $Group, ('-'*40) | Out-File -LiteralPath $OutFile -Append
    
            $Members = Get-ADGroupMember -Identity $Group -Recursive | 
                Select-Object -ExpandProperty SamAccountName
    
            foreach ($M in $Members) {
                Write-Verbose "Adding user $M"
                Out-File -InputObject $M -LiteralPath $OutFile -Append
            } 
        }
    }
    
    Export-ADGroupMembersToFile -ImportFile 'S:\Test\Input_Test\GroupNames.txt' -SaveFolder 'S:\Test\Input_Test' -Verbose
    

    这将输出一个包含所有 GroupNames 的文件。

    【讨论】:

    • 根据您的要求更新答案。如果您移除-Verbose 开关,您将看不到输出。我想一个功能总是更好。它使东西便携。如果您想更改它并希望在函数中的某个位置停止,请在 PowerShell ISE 中使用F9 设置PSBreakPoint。它允许您检查变量的内容。
    • 非常感谢 DarkLite1!第二个是一个很好的基础。经过一些修改后,它就像一个魅力:)
    • 太棒了!很高兴它帮助了你。请记住,继续探索!每次玩它都会变得更好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2016-04-25
    • 2019-09-20
    相关资源
    最近更新 更多