如何抑制PowerShell循环中New-LocalUser生成的用户对象输出?
问题:PowerShell脚本末尾自动输出新建用户对象,如何抑制
我是PowerShell脚本编写新手,参考网络资源写了一份脚本,运行整体正常:从CSV读取数据,测试并创建本地用户、添加到组,同时自定义输出每一步结果。但遇到一个问题:创建新用户后,脚本末尾会自动输出所有新建用户的对象,我没写这段输出代码,想把它去掉。
以下是我的脚本代码:
param( $FilePath ) # Setup $Count_Attempted = 0 $Count_Created = 0 $Count_MissingName =0 $Count_MissingPW = 0 $Count_MissingGroup = 0 $Count_Exists = 0 # Read the data $CSV = Import-Csv -Path $FilePath # Initial header for the output: Write-Host " ------------- STARTED SCRIPT: $(Get-Date) ------------- `r`n" # Loop through each row containing user details in the csv file ForEach ($User in ($CSV)) { $Count_Attempted++ # REQUIRED items $Username = $User.'UserName' $Password = $User.'UserPassword' if ( $Password -ne "" ){ $SecurePW = ConvertTo-SecureString $Password -AsPlainText -Force -ErrorAction SilentlyContinue } $Group = $User.'Group' # Nice, but optional: $FirmName = $User.'NameOfFirm' $FirmNumber = $User.'VendorNumber' $Fullname = (Get-Culture).TextInfo.ToTitleCase($User.'firstname'.ToLower()) + " " + (Get-Culture).TextInfo.ToTitleCase($User.'lastname'.ToLower()) $Description = "$FirmNumber|$FirmName" $Description = $Description.subString(0, [System.Math]::Min(48, $Description.Length)) # ------------- Start-header for the output: write-host "$Username|$FullName`: " -NoNewline if ( $Username -eq "" ) { write-host "Missing Username - skipping" -ForegroundColor Yellow $Count_MissingName++ } elseif ( $Password -eq "" ) { write-host "Missing Password - skipping" -ForegroundColor Yellow $Count_MissingPW++ } elseif ( $Group -eq "" ) { write-host "Missing Group - skipping" -ForegroundColor Yellow $Count_MissingGroup++ } else { # ============ 1: Check if the user account already exists $UserExists = get-localuser "$Username" -ErrorAction SilentlyContinue # 1a: DOES exist - skip it if ($UserExists -ne $null) { write-host "Account exists - skipping." -ForegroundColor Yellow $Count_Exists++ } # 1b: does NOT exist - create new one else{ write-host " does not exist - creating: " -NoNewline # +++++++++++ 2: Create New Local User New-LocalUser -Name $Username -Password $SecurePW -FullName $Fullname -Description $Description -ErrorAction SilentlyContinue -AccountNeverExpires # 2a: Test result: $? should be 'True' if it went OK, 'False' if it did not if ( $? -eq $true ) { Write-Host "Success;" -ForegroundColor Green -NoNewline Write-Host "`tAdding to Group - $Group`:" -NoNewline # +++++++++ 3: Add user to their Group, too Add-LocalGroupMember -Group $Group -Member $Username if ($? -eq $true ) { Write-Host " Success" -ForegroundColor Green $Count_Created++ } else { Write-Host " FAILED!" -ForegroundColor Red } } else { Write-Host "FAILED!!" -ForegroundColor Red } } # <--- END of User=create attempt } # <--- END of User entry values are good } # <--- END of FOR EACH loop - iterating over user entries in CSV # Finish Commands Write-Host "`n`nAttempted: $Count_Attempted" Write-Host "Created: $Count_Created" Write-Host "`tAlready exists: $Count_Exists" Write-Host "`tMissing Names: $Count_MissingName" Write-Host "`tMissing Password: $Count_MissingPW" Write-Host "`tMissing Group: $Count_MissingGroup" Write-Host " ------------- ENDED SCRIPT: $(Get-Date) -------------"
执行输出示例:
1 - user_jAKn|Izzy Logan: Missing Password - skipping 2 - user_iVam|Michael Hamen: does not exist - creating: Success; Adding to Group - Vendor: Success 3 - user_hwdH|Pat Napolou: does not exist - creating: Success; Adding to Group - Attorney: Success 4 - user_dcya|Susan Dennis: does not exist - creating: Success; Adding to Group - Vendor: Success 5 - user_FFfn|Carl Black: does not exist - creating: Success; Adding to Group - Vendor: Success Attempted: 5 Created: 4 Already exists: 0 Missing Names: 0 Missing Password: 1 Missing Group: 0 ^^^^^^^^^^^^ ENDED SCRIPT: 09/12/2024 14:55:17 ^^^^^^^^^^ Name Enabled Description ---- ------- ----------- user_iVam True |Premier Process Partners Of Pekipsy Pennsylvani user_hwdH True 2001|Flynn And Candleman user_dcya True 14442|Yale University School Of Medicine Treasur user_FFfn True 14442|Yale University School Of Medicine Treasur
解决方案
出现这个问题的原因是:PowerShell中,New-LocalUser这类cmdlet默认会将执行后生成的用户对象发送到输出管道。如果没有显式处理这些输出(比如赋值给变量、重定向到空),脚本执行完后,管道中剩余的对象会被自动格式化输出,也就是你看到的末尾用户列表。
解决方法很简单,只需要修改New-LocalUser那一行,把它的输出抑制掉,有三种常用方式:
- 将输出赋值给
$null(推荐,性能最优):
$null = New-LocalUser -Name $Username -Password $SecurePW -FullName $Fullname -Description $Description -ErrorAction SilentlyContinue -AccountNeverExpires
- 重定向输出到
$null:
New-LocalUser -Name $Username -Password $SecurePW -FullName $Fullname -Description $Description -ErrorAction SilentlyContinue -AccountNeverExpires > $null
- 通过
Out-Null过滤输出:
New-LocalUser -Name $Username -Password $SecurePW -FullName $Fullname -Description $Description -ErrorAction SilentlyContinue -AccountNeverExpires | Out-Null
任选一种修改后,脚本末尾就不会再自动输出新建用户的对象了。
内容的提问来源于stack exchange,提问作者J7Ts
相关产品推荐
相关产品推荐

