Powershell将对象传递给函数的正确方法

时间:2017-01-14 20:04:02

标签: powershell

我正在尝试将给定目录中找到的所有msi文件列出到文件中,然后提取这些msi文件。我试图使用foreach-object中的$ _来传递路径,但它似乎将它解释为文字,而不是传递路径。我认为$ _会传递对象,在这种情况下它将是文件路径,但它似乎没有这样的功能。将找到的文件路径传递给Export-MsiContents函数的正确方法是什么?

Function Export-MsiContents
{
   [CmdletBinding()]
   param
   (
          [Parameter(Mandatory = $true, Position=0)]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({Test-Path $_})]
    [ValidateScript({$_.EndsWith(".msi")})]
    [String] $MsiPath,

    [Parameter(Mandatory=$false, Position=1)]
    [String] $TargetDirectory
   )

if(-not($TargetDirectory))
{
    $currentDir = [System.IO.Path]::GetDirectoryName($MsiPath)
    Write-Warning "A target directory is not specified. The contents of the MSI will be extracted to the location, $currentDir\Temp"
    $TargetDirectory = Join-Path $currentDir "Temp"
}

$MsiPath = Resolve-Path $MsiPath

Write-Verbose "Extracting the contents of $MsiPath to $TargetDirectory"
Start-Process "MSIEXEC" -ArgumentList "/a $MsiPath /qn TARGETDIR=$TargetDirectory" -Wait -NoNewWindow
}

$Dir = get-childitem d:\temp\test -recurse
$List = $Dir | where {$_.extension -eq ".msi"}
$List | format-table fullname | out-file d:\temp\test\msilist.txt
$List | ForEach-Object {Export-MsiContents -MsiPath $_}

1 个答案:

答案 0 :(得分:0)

看起来您正在尝试将childitem对象指定为$MsiPath,它应该是一个字符串。 因此,您需要指定该对象中的哪个值用作$MsiPath。在这种情况下,您似乎想要传递fullname

试试这个:

$List | ForEach-Object {Export-MsiContents -MsiPath $_.fullname}
相关问题