0

В PowerShell я новичек. Нашел как вывести PID запускаемого процесса:

[Diagnostics.Process]::Start("calc").Id > out.txt

А можно ли как то запустить приложение передав ему аргументы. Далее вывести в файл out.txt как сам PID так и результат процесса?

1
  • можно, если приложение принимает аргументы 1 фев 2017 в 9:01

2 ответа 2

1
function Log([string]$logline){ 
    $time = (Get-Date -f o)
    $logline = "[" + $time + "] - " + $logline
    Write-host $logline
}

function StartProcess{
    <#
        .SYNOPSIS
            Start process
        .DESCRIPTION
            Function start process and return result object
        .PARAMETER  path
            Path to executable file
        .PARAMETER  arguments
            Process arguments
        .PARAMETER  rediroutput
            Redirect output
        .EXAMPLE
            all parameters are set by user
            PS C:\> 
        .EXAMPLE
            use default values for storageName and storageFolder
            PS C:\> 
        .INPUTS
            System.String,System.String,System.Boolean,System.Boolean
        .OUTPUTS
            Powershell object with properties: process exitcode, output, error
    #>
    Param (
        [String] $path, 
        [String] $arguments = $null,
        [bool] $wait = $true,
        [bool] $rediroutput = $true,
        [bool] $writeResultToLog = $true
    )    
    #create log files
    $guid = [System.Guid]::NewGuid().ToString() 
    $log = "$Env:TEMP\$guid.log"
    $elog = "$Env:TEMP\err$guid.log"
    "" | Out-File $log 
    "" | Out-File $elog 
    $exec = "Start-Process `"$path`"  -PassThru "
    if($rediroutput -eq $true){$exec = $exec + " -RedirectStandardOutput $log -RedirectStandardError $elog -NoNewWindow:`$true "}
    #Start-Process -ArgumentList
    if($arguments -ne $null){$exec = $exec + " -ArgumentList '" + $arguments + "'"}
    if($wait -eq $true){$exec = $exec + " -wait"}   
    $p = Invoke-Expression $exec
    $pr = @{}
    $pr.exitcode = $p.ExitCode
    $pr.output = [IO.File]::ReadAllText($log)
    $pr.error = [IO.File]::ReadAllText($elog)
    $pr.pid = $p.id 

    #remove log files
    Remove-Item $log
    Remove-Item $elog
    if($writeResultToLog){
        Log ("Exite code: " + $pr.exitcode)
        Log ("Output: " + $pr.output)
        Log ("ErrOutput: " + $pr.error)
    }
    #Clear-Host
    return $pr
}

$res = StartProcess -path ping -arguments "8.8.8.8" 

log($res)
log("pid = " + $res.pid)

результат

[2017-02-01T12:17:27.3732073+03:00] - Exite code: 0
[2017-02-01T12:17:27.3732073+03:00] - Output: 
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=2ms TTL=57
Reply from 8.8.8.8: bytes=32 time=2ms TTL=57
Reply from 8.8.8.8: bytes=32 time=2ms TTL=57
Reply from 8.8.8.8: bytes=32 time=2ms TTL=57

Ping statistics for 8.8.8.8:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 2ms, Maximum = 2ms, Average = 2ms

[2017-02-01T12:17:27.3732073+03:00] - ErrOutput: 
[2017-02-01T12:17:27.3732073+03:00] - System.Collections.Hashtable
[2017-02-01T12:17:27.3732073+03:00] - pid = 11312
1

Senior Automator, думаю ваш ответ верен прилагает сразу не сколько примеров о скриптах PS, особенно когда ты первый раз открываешь и не знаешь синтаксис. Но я из документации на собирал вот такой вариант:

(Start-Process .\Data\myprog.exe -ArgumentList '-param1 value1','-param2 value2','-param3 value3' -RedirectStandardOutput result-myprog.txt -PassThru -NoNewWindow).Id > result-pid.txt

Что в итоге создает два файла содержащую нужную информацию, без танцов с бубном.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.