![](/img/trans.png)
[英]How to count numbers less than 10 in an array using ForEach in PowerShell?
[英]Powershell | Is there a way to filter out items in an array that are less than 6 months old?
背景信息
我編寫了一個腳本,它使用 API 來獲取應用程序的所有用戶,我編寫該應用程序是為了專門獲取他們的 email 地址和他們上次登錄的時間。腳本將結果存儲在一個數組中,然后寫入該數組到 CSV 文件。 然后,我還使用另一個 API 端點編寫了一個單獨的腳本,該腳本根據我從 CSV 傳遞給它的 email 地址停用此應用程序中的用戶。
目前,我正在停用 6 個月或更長時間未登錄的用戶,並使用 Google 表格/Excel 來操作初始數據 output,以僅將結果過濾到上次登錄日期為 6 個月或更早的用戶,將其作為單獨的 CSV 導出,然后導入到停用腳本中。
這是問題!
powershell 中是否有一種方法可以完全完成數據操作,因此我可以將這些腳本鏈接成一個,或者能夠完成這些操作而無需手動操作 powershell 之外的數據?
To make things slightly more challenging (to me, as a moderately experienced powershell user, but nowhere near an expert:) is that the date format output from the API call is in this format: 2020-01-01T15:00:00Z
我的聲望點低於 50,因此無法直接發表評論,但解決方案是將日期 output 字符串轉換為 datetime 類型。 該字符串看起來采用 Zulu 日期格式,本質上是 UTC(不遵守夏令時)。
[datetime]'2020-01-01T15:00:00Z'
# Results in Wednesday, January 1, 2020 10:00:00 AM.
([datetime]'2020-01-01T15:00:00Z').AddDays(-1)
# Results in Tuesday, December 31, 2019 10:00:00 AM.
@vonPryz 提到的是,一旦完成,您可以使用 AddDays 方法並以負整數的形式添加經過的天數。
感謝@Dan 和@vonPryz 的支持——在我的結果中使用了這兩個!
對於上下文,在查詢 API 以獲取所有用戶數據的腳本中,它將他們上次登錄時間的結果存儲在“上次登錄”的 header 的值中 - 回想起來,我會使用 LastLogin 因為這意味着我沒有稍后調用時需要引號。 我還有一個 function 在使用 FileDialog 框選擇文件並將其分配給$users
后導入 CSV 文件
我還對可與 Get-Date 一起使用的其他方法進行了更多閱讀,發現還有一個 addmonths() 方法,因此使用了 addmonths(-6)
這是我用來獲得最終結果的代碼
$currentDate = get-date
$filterDate = $currentDate.addmonths(-6)
$newTable = @()
Foreach($user in $users){
$lastLogin = $user.'last login'
if ($lastLogin -eq "") {
} else {
$convertedLastLogin = [datetime]$lastlogin
}
if ($convertedLastLogin -lt $filterDate -or $lastlogin -lt $filterDate) {
$newTable += $user
}
}
然后,如果我願意,我可以將$newTable
output 導出到 CSV。 我將其與手動操作時獲得的數據進行了比較,它也非常匹配,所以我很確定我最終到達了那里!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.