我从.xml文件中读取了一个字符串。它看起来像这样:
<ExcludedFiles>'a.txt','b.txt','c.txt'</ExcludedFiles>
将分配变量$ exlude:
$exclude = 'a.txt','b.txt','c.txt'
我想将它传递给数组'@',以便在Get-item中使用“-excelude”参数:
Get-ChildItem $_ -name -exclude $exclude ...
但它不起作用。也许我应该逃避“,”?
它仅适用于直接分配,例如:
$exclude = @('a.txt','b.txt','c.txt')
非常感谢您的提示!最好的问候
答案 0 :(得分:0)
我做了一些例子,你可以看到它取决于powershell如何看到这个值,如果它是一个字符串它不会工作你需要在数组中转换它,也不要忘记剥离“或”。
解决方案:
$exclude = "'a.txt','b.txt','c.txt'".Split(',').Replace("'","")
示例输出:
Example 1 | "'a.txt','b.txt','c.txt'"
' a .
String System.Object
String System.Object
a.txt
b.txt
c.txt
d.txt
e.txt
f.txt
Example 2 | "'a.txt','b.txt','c.txt'".Split(',')
'a.txt' 'b.txt' 'c.txt'
String[] System.Array
String System.Object
String System.Object
String System.Object
a.txt
b.txt
c.txt
d.txt
e.txt
f.txt
Example 3 | 'a.txt','b.txt','c.txt'
a.txt b.txt c.txt
Object[] System.Array
String System.Object
String System.Object
String System.Object
d.txt
e.txt
f.txt
Example 4 | @('a.txt','b.txt','c.txt')
a.txt b.txt c.txt
Object[] System.Array
String System.Object
String System.Object
String System.Object
d.txt
e.txt
f.txt
Solution | "'a.txt','b.txt','c.txt'".Split(',').Replace("'","")
a.txt b.txt c.txt
Object[] System.Array
String System.Object
String System.Object
String System.Object
d.txt
e.txt
f.txt
示例代码:
cls
#test setup
New-Item -Path $env:TEMP -Name 'testfolder' -Force -ItemType Directory | Out-Null
$path = Join-Path -Path $env:TEMP -ChildPath 'testfolder\'
@('a.txt','b.txt','c.txt','d.txt','e.txt','f.txt') | % { New-Item -Path $path -Name $_ -Force | Out-Null}
#test code
"
Example 1 | `"'a.txt','b.txt','c.txt'`""
$exclude1 = "'a.txt','b.txt','c.txt'"
"$($exclude1[0]) $($exclude1[1]) $($exclude1[2])"
$exclude1.GetType() | select Name, BaseType
$exclude1 | % {$_.GetType()} | select Name, BaseType
Get-ChildItem -Path $path -Exclude $exclude1
"
Example 2 | `"'a.txt','b.txt','c.txt'`".Split(',')"
$exclude2 = "'a.txt','b.txt','c.txt'".Split(',')
"$($exclude2[0]) $($exclude2[1]) $($exclude2[2])"
$exclude2.GetType() | select Name, BaseType
$exclude2 | % {$_.GetType()} | select Name, BaseType
Get-ChildItem -Path $path -Exclude $exclude2
"
Example 3 | 'a.txt','b.txt','c.txt'"
$exclude3 = 'a.txt','b.txt','c.txt'
"$($exclude3[0]) $($exclude3[1]) $($exclude3[2])"
$exclude3.GetType() | select Name, BaseType
$exclude3 | % {$_.GetType()} | select Name, BaseType
Get-ChildItem -Path $path -Exclude $exclude3
"
Example 4 | @('a.txt','b.txt','c.txt')"
$exclude4 = @('a.txt','b.txt','c.txt')
"$($exclude4[0]) $($exclude4[1]) $($exclude4[2])"
$exclude4.GetType() | select Name, BaseType
$exclude4 | % {$_.GetType()} | select Name, BaseType
Get-ChildItem -Path $path -Exclude $exclude4
"
Solution | `"'a.txt','b.txt','c.txt'`".Split(',').Replace(`"'`",`"`")"
$exclude = "'a.txt','b.txt','c.txt'".Split(',').Replace("'","")
"$($exclude[0]) $($exclude[1]) $($exclude[2])"
$exclude.GetType() | select Name, BaseType
$exclude | % {$_.GetType()} | select Name, BaseType
Get-ChildItem -Path $path -Exclude $exclude