遍历哈希或在PowerShell中使用数组 [英] Looping through a hash, or using an array in PowerShell

查看:152
本文介绍了遍历哈希或在PowerShell中使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此(简化的)代码块通过 BCP从SQL Server中提取一组表

I'm using this (simplified) chunk of code to extract a set of tables from SQL Server with BCP.

$OutputDirectory = "c:\junk\"
$ServerOption =   "-SServerName"
$TargetDatabase = "Content.dbo."

$ExtractTables = @(
    "Page"
    , "ChecklistItemCategory"
    , "ChecklistItem"
)

for ($i=0; $i -le $ExtractTables.Length – 1; $i++)  {
    $InputFullTableName = "$TargetDatabase$($ExtractTables[$i])"
    $OutputFullFileName = "$OutputDirectory$($ExtractTables[$i])"
    bcp $InputFullTableName out $OutputFullFileName -T -c $ServerOption
}

它很好用,但是现在某些表需要通过视图来提取,而有些则不需要。所以我需要这样的数据结构:

It works great, but now some of the tables need to be extracted via views, and some don't. So I need a data structure something like this:

"Page"                      "vExtractPage"
, "ChecklistItemCategory"   "ChecklistItemCategory"
, "ChecklistItem"           "vExtractChecklistItem"

我在看哈希,但是我我没有找到关于如何遍历哈希的任何信息。在这里做什么正确的事?也许只是使用一个数组,但两个值都用空格隔开?

I was looking at hashes, but I'm not finding anything on how to loop through a hash. What would be the right thing to do here? Perhaps just use an array, but with both values, separated by space?

还是我遗漏了一些明显的东西?

Or am I missing something obvious?

推荐答案

克里斯蒂安的答案很好用,它显示了如何使用 GetEnumerator 方法遍历每个哈希表项。您还可以使用 keys 属性循环浏览。下面是一个示例示例:

Christian's answer works well and shows how you can loop through each hash table item using the GetEnumerator method. You can also loop through using the keys property. Here is an example how:

$hash = @{
    a = 1
    b = 2
    c = 3
}
$hash.Keys | % { "key = $_ , value = " + $hash.Item($_) }

输出:

key = c , value = 3
key = a , value = 1
key = b , value = 2

这篇关于遍历哈希或在PowerShell中使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆