Поделиться через


Process.MachineName Свойство

Определение

Возвращает имя компьютера, на котором выполняется связанный процесс.

public:
 property System::String ^ MachineName { System::String ^ get(); };
public string MachineName { get; }
[System.ComponentModel.Browsable(false)]
public string MachineName { get; }
member this.MachineName : string
[<System.ComponentModel.Browsable(false)>]
member this.MachineName : string
Public ReadOnly Property MachineName As String

Значение свойства

Имя компьютера, на котором выполняется связанный процесс.

Атрибуты

Исключения

Процесс не связан с этим Process объектом.

Примеры

Чтобы использовать следующий пример, сначала необходимо запустить хотя бы один экземпляр Блокнота на удаленном компьютере. В примере запрашивается имя удаленного компьютера, на котором выполняется Блокнот, а затем отображаются соответствующие ProcessNameIdсвойства и MachineName свойства для каждого экземпляра.

using System;
using System.Diagnostics;

class GetProcessesByNameClass
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Create notepad processes on remote computer");
        Console.Write("Enter remote computer name : ");
        string remoteMachineName = Console.ReadLine();

        if (remoteMachineName == null)
        {
            // Prepend a new line to prevent it from being on the same line as the prompt.
            Console.WriteLine(Environment.NewLine + "You have to enter a remote computer name.");
            return;
        }

        try
        {
            // Get all notepad processess into Process array.
            Process[] myProcesses = Process.GetProcessesByName("notepad", remoteMachineName);

            if (myProcesses.Length == 0)
                Console.WriteLine("Could not find notepad processes on remote computer.");

            foreach (Process myProcess in myProcesses)
            {
                Console.WriteLine(
                    $"Process Name : {myProcess.ProcessName}\n" +
                    $"Process ID   : {myProcess.Id}\n" +
                    $"MachineName  : {myProcess.MachineName}");
            }
        }
        catch (ArgumentException)
        {
            Console.WriteLine($"The value \'{remoteMachineName}\' is an invalid remote computer name.");
        }
        catch (InvalidOperationException)
        {
            Console.WriteLine("Unable to get process information on the remote computer.");
        }
        catch (PlatformNotSupportedException)
        {
            Console.WriteLine(
                "Finding notepad processes on remote computers " +
                "is not supported on this operating system.");
        }
    }
}
open System
open System.Diagnostics

printfn "Create notepad processes on remote computer"
printf "Enter remote computer name : "
let remoteMachineName = stdin.ReadLine()

if isNull remoteMachineName then
    // Prepend a new line to prevent it from being on the same line as the prompt.
    printfn "\nYou have to enter a remote computer name."
else
    try
        // Get all notepad processess into Process array.
        let myProcesses = Process.GetProcessesByName("notepad", remoteMachineName)

        if myProcesses.Length = 0 then
            printfn "Could not find notepad processes on remote computer."

        for myProcess in myProcesses do
            printfn $"Process Name : {myProcess.ProcessName}\n"
            printfn $"Process ID   : {myProcess.Id}\n"
            printfn $"MachineName  : {myProcess.MachineName}"
    with
    | :? ArgumentException -> printfn $"The value '{remoteMachineName}' is an invalid remote computer name."
    | :? InvalidOperationException -> printfn "Unable to get process information on the remote computer."
    | :? PlatformNotSupportedException ->
        printfn "Finding notepad processes on remote computers is not supported on this operating system."
Imports System.Diagnostics

Class GetProcessesByNameClass

    'Entry point which delegates to C-style main Private Function
    Public Overloads Shared Sub Main()
        Main(Environment.GetCommandLineArgs())
    End Sub

    Public Overloads Shared Sub Main(ByVal args() As String)
        Console.WriteLine("Create notepad processes on remote computer")
        Console.Write("Enter remote computer name : ")
        Dim remoteMachineName As String = Console.ReadLine()

        If remoteMachineName Is Nothing Then
            ' Prepend a new line to prevent it from being on the same line as the prompt.
            Console.WriteLine(Environment.NewLine + "You have to enter a remote computer name.")
            Return
        End If

        Try
            ' Get all notepad processess into Process array.
            Dim myProcesses As Process() = Process.GetProcessesByName _
                                                ("notepad", remoteMachineName)
            If myProcesses.Length = 0 Then
                Console.WriteLine("Could not find notepad processes on remote computer.")
            End If
            Dim myProcess As Process
            For Each myProcess In myProcesses
                Console.WriteLine("Process Name : " & myProcess.ProcessName &
                            "  Process ID : " & myProcess.Id &
                            "  MachineName : " & myProcess.MachineName)
            Next myProcess
        Catch e As ArgumentException
            Console.WriteLine("The value '" & remoteMachineName & "' is an invalid remote computer name.")
        Catch e As PlatformNotSupportedException
            Console.WriteLine(
                "Finding notepad processes on remote computers " &
                "is not supported on this operating system.")
        Catch e As InvalidOperationException
            Console.WriteLine("Unable to get process information on the remote computer.")
        End Try
    End Sub
End Class

Комментарии

Статистические данные и сведения о процессе для процессов, выполняемых на удаленных компьютерах, но не удается вызвать StartCloseMainWindowили Kill на удаленных компьютерах.

Замечание

При выполнении связанного процесса на локальном компьютере это свойство возвращает период (".") для имени компьютера. Для получения правильного имени компьютера следует использовать Environment.MachineName свойство.

Применяется к

См. также раздел