当前版本的问题:
我按如下方式初始化数组$ 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
完美无缺。有什么建议?
解决方案
以下两个答案都是正确的,但我只能选择一个。
在确定变量是一个数组之后,我不得不删除前导和尾随引号并且脚本有效。谢谢!
答案 0 :(得分:2)
$ tbd_list.GetType()。FullName提供System.String
虽然你的问题不清楚你是如何定义$ tbd_list的,但它应该是一个数组,只有当它是一个数组时它才能与Get-ChildItem
的{{1}}选项一起使用。如果它是一个字符串,它将不会以你期望的方式工作。正确定义:
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 = @()
答案 1 :(得分: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('"')
答案 2 :(得分:-1)
$pattern="packages","obj","bin" # needs to be string[]
或
[string[]] $pattern="packages","obj","bin"
Get-ChildItem -Recurse -Name -Attributes H,!H -Directory -Include $pattern