我有一個腳本,其中的一部分需要運行3次不同的時間,所以我想通過調用相同的代碼使用函數來擴展我有限的PowerShell知識,而不是複製和一次又一次地粘貼,並製作比必要的腳本更長的時間。Powershell在foreach函數中更改變量名
我想重新使用一個函數的代碼:
$users=get-content users.txt
foreach ($user in $users){
#Get some info from Exchange about the user
$dn=(get-mailboxstatistics -id $user).displayname
$ic=(get-mailboxstatistics -id $user).itemcount
#Make a hash table where user=itemcount
[email protected]{"$dn"="$ic"} #each time the script runs, we need a different hash table
#Kick off some Exchange maintenance on the user. (Removed to keep post shorter)
#Item count should lower after a few seconds.
}
當代碼重複第二次,第三次,我希望這是創造了一個新的哈希表(「secondrun」和「thirdrun 「)。我的第一個問題是每次更改函數中哈希表名稱的名稱 - 可以這樣做嗎?
我也開始懷疑哈希表是否甚至是工作的正確工具或者是否有更好的工具?對於一個小的更多背景後,我有第二個哈希表,我希望做一個比較:
foreach ($user in $users){
$c1=$firstrun.get_item($user)
$c2=$secondrun.get_item($user)
#If the item count hasn't substantially dropped
if ($c2 -ge $c1){
#Do some different Exchange tasks on the user (removed to keep post shorter)
}
}
最後就會有一個第三輪,這將簡單地創建第三哈希表(再次,用戶= ITEMCOUNT)。然後,我將使用每個散列表中的值將某種報告輸出到文本文件。
我想在這個階段我有兩個主要問題 - 函數中的哈希表有變化的變量名稱,並且我在函數運行後維護哈希表時很困難 - 試圖將它們聲明爲全局變量似乎不起作用。我很樂意提供有關如何更好地完成這些任務的想法。
感謝您的幫助!
有趣 - 這看起來也是有效的選擇。我也剛剛瞭解了比較陣列中的元素 - 謝謝! – user2158764 2013-03-12 02:54:23