6

当前版本的问题:

我初始化一个数组 $tbd_list 如下:

$tbd_list = @()
foreach($i in $tbd) {
    # -- If statement prevents duplicate id's
    if(!($tbd_list -match $i.id)){
        $tbd_list += $i.id
    }
}

此时,如果我打印 $tbd_list 我得到:

"dce50fdd-2298-45db-8aac-fb13a176fe1a*.*"
"79c1538f-09b1-4ed7-b84c-ff1a7934596a*.*"
"60511686-7a87-4352-a781-62e7c04913e5*.*"
"0821f8ee-c1ca-4568-ab68-bb5e30d07268*.*"
"3b9f5da0-fc2d-49e3-a11d-943f5ac2296a*.*"
"ff7720fd-2c0f-43c8-871a-e283f231c823*.*"

($tbd_list.GetType().FullName 返回 System.Object)

然后我尝试运行以下代码:

Get-ChildItem F:\store_test\ -Recurse -Include $tbd_list

但是,我没有得到任何回报。

但是,如果我手动输入:

$tbd_list = "dce50fdd-2298-45db-8aac-fb13a176fe1a*.*", "79c1538f-09b1-4ed7-b84c-ff1a7934596a*.*", "60511686-7a87-4352-a781-62e7c04913e5*.*", "0821f8ee-c1ca-4568-ab68-bb5e30d07268*.*", "3b9f5da0-fc2d-49e3-a11d-943f5ac2296a*.*", "ff7720fd-2c0f-43c8-871a-e283f231c823*.*"

此时,如果我打印 $tbd_list 我仍然得到:

"dce50fdd-2298-45db-8aac-fb13a176fe1a*.*"
"79c1538f-09b1-4ed7-b84c-ff1a7934596a*.*"
"60511686-7a87-4352-a781-62e7c04913e5*.*"
"0821f8ee-c1ca-4568-ab68-bb5e30d07268*.*"
"3b9f5da0-fc2d-49e3-a11d-943f5ac2296a*.*"
"ff7720fd-2c0f-43c8-871a-e283f231c823*.*"

并运行同一行($tbd_list.GetType().FullName 仍返回 System.Object):

Get-ChildItem F:\store_test\ -Recurse -Include $tbd_list

它完美地工作。有什么建议么?

解决方案

以下两个答案都是正确的,但我只能选择一个。

在确保变量是一个数组之后,我必须删除前导引号和尾随引号,脚本才能工作。谢谢!

4

3 回答 3

5

$tbd_list.GetType().FullName 给出 System.String

虽然从您的问题中看不出您是如何定义 $tbd_list 的,但它应该是一个数组,并且只有当它是一个数组时,它才能与Get-ChildItem'Include选项一起使用。如果它是一个字符串,它将不会以您期望的方式工作。正确定义它:

$tbd_list = "dce50fdd-2298-45db-8aac-fb13a176fe1a*.", "79c1538f-09b1-4ed7-b84c-ff1a7934596a.*", "dce50fdd-2298-45db-8aac-fb13a176fe1a*.", "79c1538f-09b1-4ed7-b84c-ff1a7934596a.*", "dce50fdd-2298-45db-8aac-fb13a176fe1a*.", "60511686-7a87-4352-a781-62e7c04913e5.*", "0821f8ee-c1ca-4568-ab68-bb5e30d07268*.", "3b9f5da0-fc2d-49e3-a11d-943f5ac2296a.*", "ff7720fd-2c0f-43c8-871a-e283f231c823*.*"

使用上面的行对我有用Get-ChildItem

更新:

这是你做错的地方:

$tbd_list = "$tbd_list, " + $i.id

它将构造一个字符串。

您必须初始化$tbd_list为数组:

$tbd_list = @()

并添加您想要的项目:

$tbd_list += $i.id
于 2012-04-09T15:08:26.770 回答
1

$i.id不应包含引号字符。在命令行上,它们指定一个字符串,但是当这些字符是存储在字符串变量中的字符串的一部分时,它对您不起作用,例如:

9 >  gci t*.txt


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Users\Keith


Mode           LastWriteTime       Length Name
----           -------------       ------ ----
-a---      4/3/2012  8:54 PM           13 test.txt
-a---    10/20/2011  9:13 AM         2872 trace.txt


10 >  $a = "`"t*.txt`""
11 >  $a
"t*.txt"
12 >  gci * -Include $a

像这样去掉前导和尾随引号:

$tbd_list += $i.id.Trim('"')
于 2012-04-09T16:12:53.573 回答
0
$pattern="packages","obj","bin" # needs to be string[]

或者

[string[]] $pattern="packages","obj","bin"

Get-ChildItem -Recurse -Name -Attributes H,!H -Directory -Include $pattern
于 2018-07-19T06:15:33.833 回答