powershell 如果文件名存在,如何增加文件名?

ezykj2lf  于 2023-04-21  发布在  Shell
关注(0)|答案(1)|浏览(146)

我想生成用户所属的安全组的报告。如果文件已经存在,我如何在文件末尾增加一位数?我不熟悉这个,我将感谢您的帮助

$Users = @"
SamAccountName;
FloydS
AdamS
SvacouM
FloydS
"@ | Convertfrom-csv -Delimiter ";"

$FilePath = "C:\TEMP\"
$date = Get-Date -Format yyyy-MM-dd

Foreach ($User in $Users) {

(Get-ADUser $User.SamAccountName –Properties MemberOf).MemberOf | Get-ADGroup | Select-Object name | Export-excel -Path "$FilePath$((get-aduser $User.SamAccountName -Properties Name | select name).name) ($(Get-Date -Format "yyyy-MM-dd")).xlsx" -WorksheetName $date -AutoSize -AutoFilter -TableStyle Medium2

 }

 Write-Host "Done!"
r8xiu3jd

r8xiu3jd1#

下面将创建文件名与索引号之间的括号(像Windows会做),如果一个文件名已经存在。
我还更改了您的代码,其中您在已有信息的情况下执行了额外的Get-ADUser调用

$Users    = 'FloydS','AdamS','SvacouM'
$FilePath = 'C:\TEMP'
$today    = Get-Date -Format 'yyyy-MM-dd'

foreach ($User in $Users) {
    $adUser   = Get-ADUser $User –Properties MemberOf -ErrorAction SilentlyContinue
    if ($adUser) {
        $adGroups = $aduser.MemberOf | ForEach-Object { (Get-ADGroup -Identity $_).Name }
        # create the filename without extension combining the user name and current date
        $outBaseName = '{0} {1}' -f $adUser.Name, $today  
        # combine that into the full path and filename
        $outFullName  = Join-Path -Path $FilePath -ChildPath ('{0}.xlsx' -f $outBaseName)
        # loop while that filename already exists and add an index number until unique
        $index = 1
        while (Test-Path -Path $outFullName -PathType Leaf) {
            $outFullName  = Join-Path -Path $FilePath -ChildPath ('{0}({1}).xlsx' -f $outBaseName, $index++)
        }
        $adGroups | Export-Excel -Path $outFullName -WorksheetName $today -AutoSize -AutoFilter -TableStyle Medium2
    }
    else {
        Write-Warning "Could not find user '$User'.."
    }
}

Write-Host "Done!"

相关问题