如何将包含变量的片段声明为变量以避免使用PowerShell进行代码重复?

时间:2014-12-01 15:33:33

标签: powershell

代码段(Get-Content $_.FullName | Select-Object -First 1)被调用三次。目的是将其声明为变量以避免代码重复。

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

1 个答案:

答案 0 :(得分:2)

您可以将代码段分配给变量,如下所示:

$a = { Get-Content $_.FullName | Select-Object -First 1 }

然后随时使用& $a执行代码段(您需要将对象传递给它)。我不确定你的例子中是否有必要。