PowerShell 복사 스크립트에서 여러 문자열을 적절하게 필터링하는 방법
이 답변의 PowerShell 스크립트를 사용하여 파일 복사를 수행합니다.이 문제는 필터를 사용하여 여러 파일 형식을 포함할 때 발생합니다.
Get-ChildItem $originalPath -filter "*.htm" | `
foreach{ $targetFile = $htmPath + $_.FullName.SubString($originalPath.Length); `
New-Item -ItemType File -Path $targetFile -Force; `
Copy-Item $_.FullName -destination $targetFile }
꿈만 같죠그러나 필터를 사용하여 여러 파일 형식을 포함하려는 경우 문제가 발생합니다.
Get-ChildItem $originalPath `
-filter "*.gif","*.jpg","*.xls*","*.doc*","*.pdf*","*.wav*",".ppt*") | `
foreach{ $targetFile = $htmPath + $_.FullName.SubString($originalPath.Length); `
New-Item -ItemType File -Path $targetFile -Force; `
Copy-Item $_.FullName -destination $targetFile }
다음의 에러가 표시됩니다.
Get-ChildItem : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Filter'. Specified method is not supported.
At F:\data\foo\CGM.ps1:121 char:36
+ Get-ChildItem $originalPath -filter <<<< "*.gif","*.jpg","*.xls*","*.doc*","*.pdf*","*.wav*",".ppt*" | `
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.GetChildItemCommand
괄호 없이 여러 번 반복하고 있어요.-filter
,-include
포함을 가변으로 정의한다(예:$fileFilter
매번 위의 오류가 발생하며 항상 다음 항목을 가리킵니다.-filter
.
그에 대한 흥미로운 예외는 내가 코드화할 때-filter "*.gif,*.jpg,*.xls*,*.doc*,*.pdf*,*.wav*,*.ppt*"
오류는 없지만 결과는 표시되지 않고 콘솔로 아무것도 반환되지 않습니다.제가 실수로 불순한 사람을 코드화한 것 같아요and
그런 진술로요?
그러면 제가 무엇을 잘못하고 있으며, 어떻게 수정하면 좋을까요?
- 필터는 단일 문자열만 허용합니다. - 포함은 여러 값을 허용하지만 -Path 인수를 한정합니다.요령은 추가이다.\*
경로 끝에 있는 -Include를 사용하여 여러 내선번호를 선택합니다.공백 또는 셸 특수문자를 포함하지 않는 한 cmdlet 인수에는 따옴표가 필요 없습니다.
Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*
연속되는 여러 백슬래시는 단일 경로 구분자로 해석되므로 $originalPath가 백슬래시로 끝나는지 여부에 관계없이 동작합니다.예를 들어 다음과 같이 시도합니다.
Get-ChildItem C:\\\\\Windows
옵션에 대해 설명하겠습니다.
-Filter
하나의 패턴만 사용하기 때문에 이 문제에는 적용되지 않습니다.-Include
동작은 하지만 매우 느립니다(대부분의 경우는 전혀 문제가 없습니다).로의 파이핑은,
-Include
또한 일반 와일드카드 매칭이 아닌 regex 패턴 매칭 및 다음 예시와 같이 필요한 기타 로직에 액세스할 수 있기 때문에 가장 강력한 옵션입니다.# checking extension with regex Get-ChildItem $dir | Where-Object { $_.Extension -match '\.(xlsx?|jpe?g)$' } # checking extension and creation time Get-ChildItem $dir | Where-Object { $_.Extension -in '.xls', '.xlsx', '.jpg', '.jpeg' -and $_.CreationTime -gt $yesterday }
-Path
는, 아직 약간 고속이지만, 파일명이 아닌 풀 패스를 사용하고 있습니다.이는 사용하기 어려운 문제이며(아래의 예를 참조), 경로 패턴이 디렉토리 레벨의 가변수와 일치할 수 없기 때문에, 심플한 경우에 한정해 기능합니다.이것은 일반적인 셸과는 대조적입니다.*
1 개의 디렉토리와 일치합니다.**
는 임의의 수의 중첩된 디렉토리와 일치합니다.# simpler $paths = $dir\*.xls, $dir\*.xlsx, $dir\*.jpg, $dir\*.jpeg Get-ChildItem $paths # less repetitive $paths = 'xls', 'xlsx', 'jpg', 'jpeg' | % { Join-Path $dir *.$_ } Get-ChildItem $paths
이런 게 통할 거야(나한텐 통했어.: 「 」를 -Filter
-Include
퍼포먼스에 큰 타격을 주는 것을 포함하다-Filter
.
아래는 각 파일 유형과 개별 파일에 지정된 여러 서버/워크스테이션만 루프합니다.
##
## This script will pull from a list of workstations in a text file and search for the specified string
## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside
$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'
##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'
foreach ($server in $servers)
{
foreach ($filetype in $filetypes)
{
## below creates the search path. This could be further improved to exclude the windows directory
$serverString = "\\"+$server+"\c$\Program Files"
## Display the server being queried
write-host “Server:” $server "searching for " $filetype in $serverString
Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
#-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt
$os = gwmi win32_operatingsystem -computer $server
$sp = $os | % {$_.servicepackmajorversion}
$a = $os | % {$_.caption}
## Below will list again the server name as well as its OS and SP
## Because the script may not be monitored, this helps confirm the machine has been successfully scanned
write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp
}
}
#end script
Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")
따라서 include를 사용하는 것이 가장 쉬운 방법입니다.
http://www.vistax64.com/powershell/168315-get-childitem-filter-files-multiple-extensions.html
언급URL : https://stackoverflow.com/questions/18616581/how-to-properly-filter-multiple-strings-in-a-powershell-copy-script
'programing' 카테고리의 다른 글
앱스토어 앱 링크 방법 (0) | 2023.04.18 |
---|---|
반환 값을 사용하여 스토어드 프로시저를 호출합니다. (0) | 2023.04.13 |
NSInterger의 NSLog/printf 지정자? (0) | 2023.04.13 |
Ruby에서 문자열에 하위 문자열이 포함되어 있는지 확인하는 방법 (0) | 2023.04.13 |
SQL Server 데이터베이스로 Excel 스프레드시트 열 가져오기 (0) | 2023.04.13 |