스 니펫 (Get-Content $_.FullName | Select-Object -First 1)
을 세 번 호출합니다. 목표는 코드 중복을 피하기 위해 변수로 선언하는 것입니다.PowerShell을 사용하여 코드 중복을 피하기 위해 변수를 포함하는 코드 단편을 변수로 선언하는 방법은 무엇입니까?
Get-ChildItem "$env:ChocolateyInstall\lib\eclipse.*" -Recurse -Filter "eclipseInstall.zip.txt" |
ForEach-Object{ if (((Get-Content $_.FullName | Select-Object -First 1) -match "eclipse") -and (Test-Path -Path (Get-Content $_.FullName | Select-Object -First 1))){Remove-Item -Recurse -Force (Get-Content $_.FullName | Select-Object -First 1)}}
시도
$a = (Get-Content $_.FullName | Select-Object -First 1)
Get-ChildItem "$env:ChocolateyInstall\lib\eclipse.*" -Recurse -Filter "eclipseInstall.zip.txt" |
ForEach-Object{ if (($a -match "eclipse") -and (Test-Path -Path (Get-Content $_.FullName | Select-Object -First 1))){Write-Host "hello"}}
당신은이 같은 변수에 코드의 조각을 할당 할 수 있습니다
PS C:\Windows\system32> . "C:\temp\powershelltest\test.ps1"
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At C:\temp\powershelltest\test.ps1:1 char:19
+ $a = (Get-Content $_.FullName | Select-Object -First 1)
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentC
ommand
실제로 무엇을하려고하는지 명확하지 않습니다. 질문을 편집하고 설명 할 수 있습니까? 파이프 라인을 아직 만들지 않았기 때문에 존재하지 않는'$ _'에 접근하려하기 때문에 오류가 발생합니다. – arco444
@ arco444 코드 중복을 피하려고합니다. 동일한 스 니펫 즉,'(Get-Content $ _. FullName | Select-Object-First 1)'이 현재 3 번 호출됩니다. 질문이 업데이트되었습니다. – 030
그래도 _why_? 스크립트의 실제 목적은 무엇입니까? 올바르게 할당하고 있지만 지정하려고하는 것은 올바르지 않습니다. 즉'$ a = (..) '를 사용하는 것은 괜찮지 만 처음에는 연결하지 않고 곧바로'Get-Content $ _. Fullname'을 할 수 없습니다. – arco444