查找并运行文件

时间:2019-05-31 18:24:30

标签: powershell

我正在创建一个脚本,该脚本在其中搜索一堆嵌套文件夹以找到软件的最新版本,它们均为.msi格式。我的代码当前可以找到文件并输出,但是无法运行该文件。

我可以在ForEach的最后一行中使用Select来输出正确的文件,但是当我将其更改为Start-Process时,就会被错误轰炸。

 $path="S:\\Releases\\Program"
 $NoOfDirs=Get-ChildItem $path -Directory

 ForEach($dir in $NoOfDirs){
     Get-ChildItem  "$path\$($dir.name)" -File -Recurse | 
     Where-Object {$_.LastWriteTime -gt ([DateTime]::Now.Adddays(-1))} | 
     Select-Object @{l='Folder';e={$dir.Name}},Name,LastWriteTime | 
     Sort-Object  -pro LastWriteTime -Descending |
     Start-Process -First 1
 }

运行.msi文件时是否应该使用其他命令?

1 个答案:

答案 0 :(得分:1)

由于您的代码必须“搜索一堆嵌套文件夹” ,因此建议您使用-Recurse上的Get-ChildItem.开关 还可以使用-Filter参数将搜索限制为.MSI文件。

类似这样的东西:

$path    = "S:\Releases\Program"
$refDate = (Get-Date).Adddays(-1)

Get-ChildItem -Path $path -Filter '*.msi' -File -Recurse | 
    Where-Object {$_.LastWriteTime -gt $refDate} | 
    ForEach-Object {
        # create the arguments for msiexec.exe.
        # to find out more switches, open a commandbox and type msiexec /?
        $msiArgs  = '/i', ('"{0}"' -f $_.FullName), '/qn', '/norestart'
        $exitCode = Start-Process 'msiexec.exe' -ArgumentList $msiArgs -NoNewWindow -Wait -PassThru
        if ($exitCode -ne 0) {
            # something went wrong. see http://www.msierrors.com/tag/msiexec-return-codes/
            # to find out what the error was.
            Write-Warning "MsiExec.exe returned error code $exitCode"
        }
    }
相关问题