В настоящее время я пытаюсь запустить файл .bat примерно на 150 серверах. Я могу запустить сценарий, как будто проблем нет - .bat копируется на серверы, однако, похоже, он вообще не выполняется.
В основном работает на серверах Windows 2012.
#Variables
$servers = "D:\Apps\Davetest\servers.txt"
$computername = Get-Content $servers
$sourcefile = "D:\Apps\Davetest\test.bat"
#This section will install the software
foreach ($computer in $computername)
{
$destinationFolder = "\\$computer\C$\Temp"
<#
It will copy $sourcefile to the $destinationfolder. If the Folder does
not exist it will create it.
#>
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Invoke-Command -ComputerName $computer -ScriptBlock {Start-Process 'c:\Temp\test.bat'}
}
Я ищу его для запуска .bat, как только он попадет на серверы, и в настоящее время он только копирует.





Это потому, что Start-Process немедленно возвращается. Используйте параметр -Wait.
Start-Process -FilePath 'c:\Temp\test.bat' -NoNewWindow -Wait -PassThru
-PassThru
Returns a process object for each process that the cmdlet started. By default, this cmdlet does not generate any output.
-Wait Indicates that this cmdlet waits for the specified process and its descendants to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the processes finish.
-PassThru возвращает вам объект процесса, где вы можете проверить параметр ExitCode:
$p = Start-Process -FilePath your_command -ArgumentList "arg1", "arg" -NoNewWindow -Wait -PassThru
if ($p.ExitCode -ne 0) {
throw "Failed to clone $buildItemName from $buildItemUrl to $($tmpDirectory.FullName)"
}
В качестве альтернативы Start-Process вы также можете использовать Invoke-Expression, который вернет вам стандартный вывод консоли.
Чтобы проверить успешность Invoke-Expression, вы можете использовать:
$output = Invoke-Expression $command
if ((-not $?) -or ($LASTEXITCODE -ne 0)) {
throw "invoke-expression failed for command $command. Command output: $output"
}
Не могли бы вы также поставить мне плюс, мне нужна оценка, чтобы получить значок PowerShell. Спасибо