2013-03-11 66 views
1

我有一個腳本,其中的一部分需要運行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)。然後,我將使用每個散列表中的值將某種報告輸出到文本文件。

我想在這個階段我有兩個主要問題 - 函數中的哈希表有變化的變量名稱,並且我在函數運行後維護哈希表時很困難 - 試圖將它們聲明爲全局變量似乎不起作用。我很樂意提供有關如何更好地完成這些任務的想法。

感謝您的幫助!

回答

2

如果我理解你的說法,你正在做以下幾點:

  1. 填充一個哈希表將用戶組映射到其項目數。
  2. 做一些修剪項目
  3. 重新生成哈希表
  4. 比較步驟1 & 3生成的哈希表;再次上榜。
  5. 重新生成哈希表
  6. 產生一個報告基於所有3個表

正如你可以從上面的列表中看到,你真正想要做的是生成產生的哈希表,並返回它的功能:

function get-usersitemcount 
{ 
    $ht = @{} 
    $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"} 
    } 

    $ht #returns the hashtable 
} 

現在你可以調用這個函數3次:

$firstrun = get-usersitemcount 
# do first run stuff 
$secondrun = get-usersitemcount 
# do second run stuff 
$thirdrun = get-usersitemcount 
# generate your report 
0

如果我是你,我會怎麼做?我會假設它與哈希表的名稱無關。如果是這樣的話,你可以抓住當前日期時間並用它來命名您的哈希表,像

$HashTblName = "HashTbl_$($(get-date).ToString("yyyyMMddhhmmssff"))" 
1

爲什麼不僅僅使用一個散列表,將值作爲一個數組,每次傳遞一個元素?

$ht = @{} 

$users=get-content users.txt 
foreach ($user in $users){ 
#Get some info from Exchange about the user 
$stats = get-mailboxstatistics $user | 
select -expand itemcount 
$ht[user] += @($stats)} 
} 

#Kick off some Exchange maintenance on the user. (Removed to keep post shorter) 
#Item count should lower after a few seconds. 


foreach ($user in $users){ 
#Get some info from Exchange about the user 
$stats = get-mailboxstatistics $user | 
select -expand itemcount 
$ht[user] += @($stats) 


#If the item count hasn't substantially dropped 
if ($ht[$user][1] -ge $ht[$user][0]) 
#Do some different Exchange tasks on the user (removed to keep post shorter) 
} 

編輯 - 更改邏輯以清理語法,希望這樣可以更容易理解。

+0

有趣 - 這看起來也是有效的選擇。我也剛剛瞭解了比較陣列中的元素 - 謝謝! – user2158764 2013-03-12 02:54:23