我有一个脚本,其中一部分需要运行三次不同的时间,所以我想我会尝试通过使用函数调用相同的代码来扩展我有限的PowerShell知识,而不是一次又一次地复制和粘贴,并制作一个超过必要的脚本。
我想在函数中重用的代码:
$users = Get-Content users.txt
foreach ($user in $users){
# Get some information from Exchange about the user
$dn = (Get-MailboxStatistics -id $user).displayname
$ic = (Get-MailboxStatistics -id $user).itemcount
# Make a hash table where user=itemcount
$firstrun += @{"$dn"="$ic"} # Each time the script runs, we
# need a different hash table
# Kick off some Exchange maintenance on the user. (Removed
# to keep the 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 the post shorter)
}
}
最后还会有第三次运行,它只会创建第三个哈希表(同样,user = itemcount)。然后,我将使用每个哈希表中的值将某种报告输出到文本文件。
我想在这个阶段我有两个主要问题 - 函数中哈希表的变量名称有变化,而且在函数运行后我很难维护哈希表 - 试图将它们声明为全局变量似乎不起作用。我愿意接受有关如何更好地完成任何工作的想法。
答案 0 :(得分:2)
如果我理解你在说什么,你就是在做以下事情:
从上面的列表中可以看出,你真的想生成一个产生哈希表并返回它的函数:
function Get-UsersItemCount
{
$ht = @{}
$users = Get-Content users.txt
foreach ($user in $users){
# Get some information from Exchange about the user
$dn = (Get-MailboxStatistics -id $user).displayname
$ic = (Get-MailboxStatistics -id $user).itemcount
# Make a hash table where user=itemcount
$ht += @{"$dn"="$ic"}
}
$ht # Returns the hashtable
}
现在你可以调用这个函数三次:
$firstrun = Get-UsersItemCount
# Do first run stuff
$secondrun = Get-UsersItemCount
# Do second run stuff
$thirdrun = Get-UsersItemCount
# Generate your report
答案 1 :(得分:1)
你可以使用一个哈希表,使值成为一个数组,每个传递一个元素:
$ht = @{}
$users = Get-Content users.txt
foreach ($user in $users){
# Get some information 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 information 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 the post shorter)
}
答案 2 :(得分:0)
如果我是你,我该怎么办?我假设哈希表的名称是什么并不重要。如果是这种情况,您可以获取当前日期时间并使用它来命名哈希表,例如
$HashTblName = "HashTbl_$($(get-date).ToString("yyyyMMddhhmmssff"))"