powershell - 查找并运行文件

标签 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 文件时我应该使用不同的命令吗?

最佳答案

由于您的代码必须“搜索一堆嵌套文件夹”,因此我建议在 Get-ChildItem 上使用 -Recurse 开关。 还可以使用 -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"
        }
    }

关于powershell - 查找并运行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56400084/

相关文章:

Regex Group,捕获 IP 的问题

powershell - 在充满日志文件Powershell脚本的几个文件夹中查找错误

powershell - 简单的PowerShell脚本循环遍历1个CSV文件以从另一个CSV文件创建新的CSV文件

powershell - 在Powershell脚本中将csv/文本文件中的$替换为$

来自另一个 RunBook 的 Azure 自动化 RunBook

iis - 使用 Powershell 更改 IIS 站点主目录

regex - -匹配成功但不更新 $matches

PowerShell:如何在 PowerShell 中将数组对象转换为字符串?

c# - 通过 C#/Graph 禁用 MS Teams 邀请邮件

powershell - 在PowerShell中使用Out-GridView:如何更改窗口的初始大小?