Powershell 查找和运行文件
我正在创建一个脚本,它在其中搜索一组嵌套文件夹,以找到最新版本的软件,这些软件是.msi格式的。我的代码目前可以找到该文件并将其输出,但无法运行该文件 我可以在ForEach的最后一行使用Select来输出正确的文件,但当我将其更改为启动进程时,我会被错误轰炸Powershell 查找和运行文件,powershell,Powershell,我正在创建一个脚本,它在其中搜索一组嵌套文件夹,以找到最新版本的软件,这些软件是.msi格式的。我的代码目前可以找到该文件并将其输出,但无法运行该文件 我可以在ForEach的最后一行使用Select来输出正确的文件,但当我将其更改为启动进程时,我会被错误轰炸 $path="S:\\Releases\\Program" $NoOfDirs=Get-ChildItem $path -Directory ForEach($dir in $NoOfDirs){ Get-ChildIt
$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文件时是否应该使用其他命令?由于您的代码必须“搜索一堆嵌套文件夹”,我建议使用-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"
}
}
我猜
Start Process
不接受-First
参数…我试图为输出设置一个全局变量,然后启动进程,但仍然无法,我知道在bat文件中,我必须调用msiexec.exe才能使用它,但我相信powershell可以在没有它的情况下运行.msi。但我不确定我的信息是否正确。我不遵循逻辑,但全局变量可以工作。正如@JosefZ所提到的,启动进程
不接受-First
作为参数。如果您从foreach
中获得所需的值,可以将结果分配给$global:result
,并在foreach
之外使用Start Process$global:result
调用。如果在过去24小时内更改了多个版本,则这两个版本都将启动。使用正确的语法:|排序对象LastWriteTime-降序|选择对象-第一个1
并没有那么糟糕。(除了您的增强功能+1)这在一定程度上与安装有关。此软件提示用户授予安装2或3个库的权限,因此我认为此方法跳过了这些提示。有办法解决这个问题吗?要回答我自己的评论,以便将来需要回答,请在PowerShell硬盘上找到.exe,并将属性更改为始终以管理员权限开始。