Сценарий powershell не продолжается после ошибки.продолжай уже в коде - PullRequest
0 голосов
/ 09 апреля 2019

Я пытаюсь запустить процесс, если он не запущен на удаленных машинах.Проблема в том, что если одна из удаленных машин недоступна, сценарий просто останавливается и использует первую часть «IF» сценария.

Когда я ставлю доступную машину первой в списке, все работает.Когда я сначала ставлю недоступный компьютер, скрипт просто запускает процесс, не проверяя второй компьютер в моем списке.

Я запускаю скрипт с командным файлом от имени администратора:

powershell -Command Set-ExecutionPolicy Bypass -Force
powershell -Command "\\networkpath\bla.ps1"

Сценарий:

$ErrorActionPreference = 'SilentlyContinue'

$ProcessName = “processname”
$Computername = Get-Content \\networkpath\computernamen.txt |
                ForEach-Object { $_ -split ',' }

$ProcessActive = Get-Process $ProcessName -ComputerName $Computername -EV Err -EA SilentlyContinue

if ($ProcessActive -eq $null) {
    Start-Process -FilePath "\\networkpath\aktuell.bla"
} else {
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.MessageBox]::Show("Programm gesperrt.", "Info", 0)
}

1 Ответ

0 голосов
/ 10 апреля 2019

Если я правильно понял, вы хотите запустить команду или процесс, если другой (или такой же) процесс не запущен ни на одной из перечисленных машин, верно?

в этом случае вы можете попробовать это:

<#
.SYNOPSIS
    Runs a process if another or same process is not running on other computers.
.DESCRIPTION
    Search for a process (specified in -Process parameter) on computers (specified in -Computer or -List parameters).
    If not any process is found, it runs then another process (specifies in -Run parameter)
.PARAMETER Computer
    Specifies one or more computer name
    This value(s) can come from the pipeline
.PARAMETER List
    Specifies path of a file which contains a list of computer names
    The file can contain computer names one per line, or in one line separated by ',' or ';'
.PARAMETER Process
    Specifies the name of the process to check on computers
.INPUTS
    This script accept from pipeline one or more System.String representing computer names
.OUTPUTS
    None
#>


[CmdletBinding(DefaultParameterSetName='Default')]
Param (
    # Specifies one or more computer name
    [Parameter(Mandatory=$true,
               Position=0,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               ValueFromRemainingArguments=$false, 
               ParameterSetName='Default')]
    [ValidateNotNullOrEmpty()]
    [Alias("ComputerName")] 
    [string[]]
    $Computer,
    # Specifies path of a computer list file.
    [Parameter(Mandatory=$true,
               Position=0,
               ParameterSetName = 'FromFile')]
    [ValidateScript( { Test-Path $_ -PathType Leaf } )]
    [Alias("ListFile")]
    [string]
    $List,
    # Specifies the process name
    [Parameter(Mandatory=$true,
               Position=1)]
    [ValidateNotNullOrEmpty()]
    [Alias("ProcessName")]
    [String]
    $Process,
    # Specifies the process to run
    [Parameter(Mandatory = $true,
        Position = 2)]
    [ValidateNotNullOrEmpty()]
    [Alias("ProcessToRun")]
    [String]
    $Run
)
# Set default ErrorAction setting
$ErrorActionPreference = 'SilentlyContinue'
# If current Parameter Set is 'FromFile' (-List parameter was used followed by a file path)
If ($PSCmdlet.ParameterSetName -eq 'FromFile') {
    # For each line in the provided file...
    Get-Content -Path $List | ForEach-Object {
        # Test line:
        switch ($_) {
            # If any ',' is found in the line, then split each value separated by a ',' in Computer array of strings and process next line
            { $_ -match '*,*' } { [string[]]$Computer = $_.Split(',');continue }
            # If any ';' is found in the line, then split each value separated by a ';' in Computer array of strings and process next line
            { $_ -match '*;*' } { [string[]]$Computer = $_.Split(';');continue }
            # In any other case...
            Default {
                # If Computer variable does not exists, create an empty array of strings
                if (!$Computer) { [string[]]$Computer = @() }
                # Add line content as a new item of the Computer array of strings
                [string[]]$Computer += , $_
            }
        }
    }
}
# Set a flag to False
$isRunning = $false
# For each computer ($item) in Computer array...
foreach ($item in $Computer) {
    # If Get-Process command for provided Process on current computer found something, set flag to True
    if (Get-Process -Name $Process -ComputerName $item -ErrorVariable Err) { $isRunning = $true }
}
# If Flag equals True (If the searched Process was already running on any of the listed computers)...
if ($isRunning) {
    # Start process provided in -Run parameter
    Start-Process -FilePath $Run
# Else (no listed computer seems to run the searched process)
} else {
    #To display a message through dialog box
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.MessageBox]::Show("Your message","Title", 0) | Out-Null
    #To display a message in Console
    "Your message" | Out-Host
}

Скопируйте и сохраните его в файле PS1, затем я рекомендую вам напечатать, чтобы знать, как его использовать:

Get-Help .\YourScript.ps1 -Full

Я сделал это очень быстро и не потратил время на его тестирование. Пожалуйста, дайте мне знать, если это работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...