將執行結果輸出到檔案時會出現檔案被佔用導致有些資料沒有寫進去,我如何解決這個問題?
目前執行時會出現"Out-File : 由於另一個處理序正在使用檔案,所以無法存取該檔案。",但出現的筆數不定,漏寫的位置也不定。
請給我建議,感謝。
$Users = (Get-ADUser -Filter * | Where-Object {($_.SamAccountName -notlike 'system*') -and ($_.SamAccountName -notlike 'HealthMailbox*') -and ($_.SamAccountName -notlike 'SM_*') -and ($_.SamAccountName -notlike '$CUA000*') -and ($_.SamAccountName -notlike 'krbtgt') -and ($_.SamAccountName -notlike 'SQL*')}).SamAccountName
$Result = 'C:\temp\Result_AllUserMemberOf_in_ActiveDirectory.txt'
$AllUsersResult = 'C:\temp\Result_AllUsers_in_ActiveDirectory.txt'
$Users | Out-File $AllUsersResult
'使用者名稱' + ',' + '使用者帳號' + ',' + '使用者Email' + ',' + '使用者所屬群組' | Out-String | Out-File $Result
ForEach ($User in $Users)
{
$UserDetail = Get-ADUser -Identity $User -Properties *
$PrimaryGroup = $UserDetail.PrimaryGroup -split ","
$PrimaryGroup = ($PrimaryGroup[0]).Replace('CN=','')
$Groups = Get-ADUser $User -Properties memberOf | Select-Object -ExpandProperty memberOf | Where-Object { ($_ -like 'CN=*') -and ($_ -notlike '*靜態通訊錄*') -and ($_ -notlike '*Exchange*') -and ($_ -notlike '*Builtin*')}
$UserDetail.Name + ',' + $UserDetail.SamAccountName + ',' + $UserDetail.mail + ',' + $PrimaryGroup + ',' | Out-File $Result -Append -NoNewline | Wait-Job
ForEach ($Group in $Groups)
{
$GroupArray = $Group -split ","
$Names = ($GroupArray[0]).Replace('CN=','')
ForEach ($Name in $Names)
{
$Name +"," | Out-File $Result -Append -NoNewline | Wait-Job
}
}
"" | Out-String | Out-File $Result -Append -NoNewline | Wait-Job
}
目前在DC上或是與DC同網段VM(Win10或Win2019)上執行都不會出現錯誤,推測可能是網段造成的問題。