Скрипт который будет запускать из папки exe файлы автоматически и от имени администратора для powershell.

Galaxy

Студент 1 курс
Сообщения
708
Решения
1
Реакции
21
Мне нужен скрипт, который автоматизирует ручной запуск exe-файлов из папки. Также нужно, чтобы он запускал exe-файлы от имени администратора и нужно что бы он был написан для powershell.
 
Мне нужен скрипт, который автоматизирует ручной запуск exe-файлов из папки. Также нужно, чтобы он запускал exe-файлы от имени администратора и нужно что бы он был написан для powershell.
Для автоматизации запуска exe-файлов из папки с помощью PowerShell, вы можете использовать следующий скрипт:

PowerShell:
$folderPath = "путь_к_папке"
$exeFiles = Get-ChildItem -Path $folderPath -Filter *.exe

foreach ($file in $exeFiles) {
    Start-Process -FilePath $file.FullName -Verb RunAs
}

Этот скрипт будет искать все exe-файлы в указанной папке и запускать их от имени администратора. Пожалуйста, убедитесь, что указали правильный путь к папке в переменной $folderPath.
 
А как запустить этот скрипт?
Чтобы запустить PowerShell скрипт, вам нужно выполнить следующие шаги:

1. Откройте редактор PowerShell (PowerShell ISE или любой другой текстовый редактор).
2. Вставьте скрипт, который я предоставил в предыдущем сообщении, в редактор.
3. Измените значение переменной $folderPath на путь к папке, содержащей ваши exe-файлы.
4. Сохраните скрипт с расширением ".ps1" (например, "run_exe_files.ps1").
5. Запустите PowerShell от имени администратора.
6. Используйте команду Set-ExecutionPolicy RemoteSigned, если требуется разрешение запуска скриптов.
7. Затем выполните команду .\run_exe_files.ps1 для запуска вашего скрипта.

Пожалуйста, убедитесь, что путь к папке указан правильно и что у вас есть необходимые права для запуска скрипта.
 
Не работает. Выдаёт ошибку:не распознано как имя командлета, функции, файла сценария или выполняем ой программы. Проверьте правильность написания имени, а также наличие и правильность пути, после чего повторите попытку. (путь написал правильно)
 
Не работает. Выдаёт ошибку:не распознано как имя командлета, функции, файла сценария или выполняем ой программы. Проверьте правильность написания имени, а также наличие и правильность пути, после чего повторите попытку.
Кажется, возникла проблема с выполнением скрипта из-за политики выполнения скриптов PowerShell. Для решения этой проблемы, попробуйте следующие шаги:

1. Запустите PowerShell от имени администратора.
2. Введите команду Set-ExecutionPolicy Unrestricted и подтвердите изменение политики выполнения скриптов.
3. Попробуйте снова запустить скрипт, следуя указанным ранее шагам.

Если после выполнения этих шагов проблема сохраняется, пожалуйста, дайте мне знать, чтобы мы могли рассмотреть другие возможные причины ошибки.
 
Код:
# Get the path of the directory where this script is located
$folderPath = Split-Path -Parent $MyInvocation.MyCommand.Path

# Get all .exe files in the folder
$exeFiles = Get-ChildItem -Path $folderPath -Filter *.exe

# Loop through each .exe file and run it as administrator
foreach ($exe in $exeFiles) {
    $processInfo = New-Object System.Diagnostics.ProcessStartInfo
    $processInfo.FileName = $exe.FullName
    $processInfo.Verb = "runas" # This will run the .exe as administrator
    $processInfo.UseShellExecute = $true

    try {
        # Start the process
        $process = [System.Diagnostics.Process]::Start($processInfo)
        # Wait for the process to finish before continuing to the next one
        $process.WaitForExit()
    } catch {
        Write-Host "Failed to run $($exe.FullName): $_"
    }
}

Right click the .ps1 and create a shortcut-- save where you want.
Drag Drop any .exe into the folder., then right click the shortcut run as admin.
 
Код:
# Get the path of the directory where this script is located
$folderPath = Split-Path -Parent $MyInvocation.MyCommand.Path

# Get all .exe files in the folder
$exeFiles = Get-ChildItem -Path $folderPath -Filter *.exe

# Loop through each .exe file and run it as administrator
foreach ($exe in $exeFiles) {
    $processInfo = New-Object System.Diagnostics.ProcessStartInfo
    $processInfo.FileName = $exe.FullName
    $processInfo.Verb = "runas" # This will run the .exe as administrator
    $processInfo.UseShellExecute = $true

    try {
        # Start the process
        $process = [System.Diagnostics.Process]::Start($processInfo)
        # Wait for the process to finish before continuing to the next one
        $process.WaitForExit()
    } catch {
        Write-Host "Failed to run $($exe.FullName): $_"
    }
}

Right click the .ps1 and create a shortcut-- save where you want.
Drag Drop any .exe into the folder., then right click the shortcut run as admin.
It looks like you have provided an alternative PowerShell script to automate the execution of exe files from a folder. This script retrieves the path of the directory where the script is located, gets all .exe files in that folder, and then runs each .exe file as an administrator.

To use this script, follow these steps:
1. Copy and paste the provided script into a new PowerShell script file (with a .ps1 extension).
2. Save the script file.
3. Right-click on the script file and select "Create shortcut."
4. Move the shortcut to the folder where you have your .exe files.
5. Drag and drop any .exe file into that folder.
6. Right-click on the shortcut you created and select "Run as administrator" to execute the script and run the .exe files as an administrator.

This method should help automate the process of running exe files from a folder as an administrator. Let me know if you encounter any issues or need further assistance.
 
Назад
Сверху Снизу