问题
I want to use an array for the exclusion:
Remove-Item -Path "$InstallDir\Lang\*" -Exclude "de.txt", "en.txt"
or
Get-ChildItem "$InstallDir\Lang" -EXCLUDE "es.txt", "de.txt"| Remove-Item
These both work fine.
Whereas
Get-ChildItem "$InstallDir\Lang\*" -Exclude "$Language" | remove-item
does not work.
I tried several ways ( e.g. How to use Get-ChildItem with filter array in Powershell? or How to exclude list of items from Get-ChildItem result in powershell?) but I can´t find a solution.
It seems as if $Language
can't be interpreted by the command.
This is how $language
is built:
[string]$Language = @('"de.txt"')
If ($PackageConfigFile.Language -notlike $Null) {
foreach ($LIP in $PackageConfigFile.Language) {
$Language += ",`n ""$LIP.txt"""
}
}
$language has e.g. the following content
"de.txt",
"en.txt",
"es.txt"
Has anybody an idea?
回答1:
First:
Construct your $Language
argument as an actual PowerShell array; what you attempted creates a multil-line string instead.
Creating that array should be as simple as:
$Language = $PackageConfigFile.Language -replace '$', '.txt'
-replace
, with a collection (array) as the LHS, operates on each item in the collection individually; '$', '.txt'
effectively appends .txt
to the end ($
) of each input item, and the resulting modified elements are collected in $Language
as an array, of .NET type System.Object[]
.
Second:
Do not enclose $Language
, your array argument, in "..."
.
Get-ChildItem $InstallDir\Lang\* -Exclude $Language | Remove-Item -WhatIf
If you enclose an array variable in "..."
, PowerShell converts it to a single string, composed of the array elements concatenated with the value of preference variable $OFS
, which defaults to a space; e.g.:
PS> $arr = 'a', 'b', 'c'; "[$arr]"
[a b c]
For readers coming from a UNIX / bash
background:
PowerShell variables do NOT need to be double-quoted when they're passed to other commands, whatever they may contain (spaces or other shell metacharacters).
When calling PowerShell-native functionality (cmdlets, functions, scripts), the variable's original type is preserved as-is (the ability to use the .NET Framework's rich type system is the core feature that exemplifies PowerShell's evolutionary quantum leap in the world of shells).
Only use "..."
if you explicitly want to pass a string to the target command.
回答2:
$Language = @('de.txt')
If ($PackageConfigFile.Language -notlike $Null) {
foreach ($LIP in $PackageConfigFile.Language) {
$Language += "$LIP.txt"
}
}
来源:https://stackoverflow.com/questions/46866889/how-to-use-get-childitem-with-excluding-a-list-of-items-with-an-array-in-powersh