简体   繁体   中英

Powershell proper way to pass object to function

I am trying to list all msi files found in a given dir to a file, then extract those msi files. I am trying to use the $_ in the foreach-object to pass the path however it seems to be interpreting it as a literal, instead of passing the path. I thought the $_ would pass the object, which in this case would be the filepath, but it doesnt seem to be functioning that way. What is the proper way to pass the found filepaths to the Export-MsiContents function?

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 $_}

It looks like you are trying to specify a childitem object as the $MsiPath which should be a string. So you would need to specify which value in that object to use as $MsiPath . In this case it looks like you would like to pass the fullname .

Try this:

$List | ForEach-Object {Export-MsiContents -MsiPath $_.fullname}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM