2016-02-12 69 views
0

我試圖導出用戶列表,獲取這些用戶的隨機樣本,然後從原始列表中刪除該隨機樣本。如果我手動添加數據到這個數組像這樣Technet article它似乎工作正常。但是當我嘗試從csv導入或使用Get-Content獲取數據時,它不會刪除任何內容。任何幫助將不勝感激。更新Powershell中的變量陣列

<#-->The first 4 lines are the same for all attempts. Between attempts I exited PowerShell.<--#> 

$Date = Get-Date -DisplayHint Date 
Get-ADUser -Filter * -SearchBase "OU=Users,DC=Domain" -SearchScope OneLevel -Properties sAMAccountName | 
Select-Object @{Name="User ID";Expression={$_."sAMAccountName"}}, @{Name="Date";Expression={$Date}} | 
Export-Csv "C:\File.csv" -NoTypeInformation 

#-->First Attempt<--# 
$Import = Import-Csv C:\File.csv 
$Sample = Get-Random -InputObject $Import -Count 20 
$List = $Import -ne $Sample 

#This shows 20. 
$Sample.Count 

#These both show the same number instead of $List being 20 less than $Import. 
$Import.Count 
$List.Count 

#-->Second Attempt<--# 
$Import = Get-Content C:\File.csv 
$Sample = Get-Random -InputObject $Import -Count 20 
$List = $Import -ne $Sample 

#This shows 20. 
$Sample.Count 

#These both show the same number instead of $List being 20 less than $Import. 
$Import.Count 
$List.Count 

#-->Third Attempt<--# 
[System.Collections.ArrayList]$Import = Import-Csv C:\File.csv 
[System.Collections.ArrayList]$Sample = Get-Random -InputObject $Import -Count 20 
[System.Collections.ArrayList]$List = $Import -ne $Sample 

#This shows 20. 
$Sample.Count 

#These both show the same number instead of $List being 20 less than $Import. 
$Import.Count 
$List.Count 

#-->Fourth Attempt<--# 
[System.Collections.ArrayList]$Import = Import-Csv C:\File.csv 
[System.Collections.ArrayList]$Sample = Get-Random -InputObject $Import -Count 20 
[System.Collections.ArrayList]$List = $Import.Remove($Sample) 

#This shows 20. 
$Sample.Count 

#This shows 1000. 
$Import.Count 

#This shows 0. 
$List.Count 
+0

我想你想這樣:'$ List =(Compare-Object -ReferenceObject $ Import -DifferenceObject $ Sample).InputObject'。 –

+0

@AlexanderObersht 謝謝,這個作品。 – pshellnewb

回答

0

使用Where語句來過濾掉你不希望包括記錄,如獲取這些值過:

$Import = Import-Csv C:\File.csv 
$Sample = Get-Random -InputObject $Import -Count 20 
$List = $Import | Where{$_ -notin $Sample} 

然後$List.count應該是$Import.Count - $Sample.Count

+0

謝謝你的回覆,這也適用於我。 – pshellnewb

0

你想這是亞歷山大提到:

$List = (Compare-Object -ReferenceObject $Import -DifferenceObject $Sample).InputObject | Where-Object { $_.SideIndicator -eq '<=' } 

$_.SideInidcator將只得到你在$Import的值,而不是在$Sample

編輯:

其實自名稱都在列表中Alexanders方法將工作得很好。但是,如果你在$sample這不是在$Import過值,那麼你會除非你做了sideIndicator方法

+0

當我添加'code' | Where-Object {$ _。SideIndicator -eq'<='}'code' $ List是空的。儘管如此,它正在做我想要的東西,所以稍後我會在這個管道中玩弄一下,看看我能用它做些什麼。 – pshellnewb