【运维】Powershell 服务器系统管理信息总结

简介: Powershell 服务器系统管理信息总结(进程、线程、磁盘、内存、网络、CPU、持续运行时间、系统账户、日志事件)

Powershell 服务器系统管理信息总结

进程、线程、磁盘、内存、网络、CPU、持续运行时间、系统账户、日志事件...


李俊才(jcLee95) 的个人博客
已入驻阿里云博客
邮箱 :291148484@163.com


本文地址
- https://developer.aliyun.com/article/
- https://blog.csdn.net/qq_28550263/article/details/125318245

目 录


1. 简单示例与说明

2. 功能查询

3. sysinfos源代码


1. 简单示例与说明

1.1 直接使用

函数均为静态函数,因此通过类进行调用而不是类的实例。返回值以数组和哈希表居多,如:

6666666666666.png

由于可能存在对象的嵌套,而powershell终端在现实这些对象时并不会嵌套现实,因此如果你想看到更多的层次,可能需要对这些对象进行序列化,比如转化为JSON格式进行显示,如:

[sysinfos]::GetDiskUsage() | ConvertTo-Json

效果如下:

6666666666666.png

可以看到,这个方法输出了当前主机上所有磁盘的使用信息(剩余容量、总容量以及使用率)。

再如,由于在Winserver 2012 以前的系统,Powershell 没有Get-NetAdapter命令,若也想在这些系统上通过 powershell 查看网络设配器信息,可以使用GetNetAdapter方法:

[sysinfos]::GetNetAdapter()


效果如下:


6666666666666.png


同样,你也可以将这些信息转换为JSON的格式进行现实:

[sysinfos]::GetNetAdapter() | ConvertTo-Json


6666666666666.png


或者直接将这些信息输出为一个.json文档,如:

[sysinfos]::GetNetAdapter() | ConvertTo-Json > C:\Users\a2911\Desktop\NetAdapterInfos.json

运行后将在指定的位置生成相应文本文档

6666666666666.png

6666666666666.png

更多的方法与对应功能的描述请参考 2. 功能查询 小节。

1.2 在脚本中使用

以下是以一个从我日常脚本中截取出来的一段,用于运维时获取某台服务器的相关数据,提交到指定的数据集中服务器上以集中管理数据。可以在Windows任务计划中添加定时任务,以定时向数据管理的服务器来提交最新的服务器运行数据。

using module .\jcstdio\os.psm1
using module .\jcstdio\http.psm1
$body = @{
    HostName = "MYSERVER_XX";
    IPAddress = [sysinfos]::GetIpAddress();              # 获取IP相关数据
    CPU_Load = [sysinfos]::GetCPULoad();                 # 获取CPU使用率,数组(针对多CUP、多核心)
    Drive_Space = [sysinfos]::GetDiskUsage();            # 各个硬盘分区的使用情况
    MemoryInfos = [sysinfos]::GetMemoryInfos();          # 内存相关信息,如使用率
    System_Running_Time = [sysinfos]::GetSystemRunningTime();
    Java_Service = [sysinfos]::GetProcessInfos()["JavaService.exe"];
    Oracle_Service = [sysinfos]::GetProcessInfos()["oracle.exe"];
    JBoss_Services =   [sysinfos]::GetServiceInfos()["JBoss"];
};
$requests = [requests]::new();
$requests.post("http://xx.xx.xx:xxxx/xxx/",($body | ConvertTo-Json))

2. 功能查询

函数名 描述
GetServiceInfos 获取指定服务的相关数据
GetProcessInfos 获取所有进程的相关数据
IP4RouteTable 表示控制网络数据包路由的信息
GetSystemRunningTime 获取系统持续运行时间
GetCPULoad 获取CUP各核心使用率
GetThread 获取执行线程
GetNetAdapter 获取网络适配器信息
GetIpAddress 从ipconfig中获取各网络硬件地址信息
GetNetAdapterByDeviceID
GetNetAdapterByName
GetNetAdapterByMACAddress
GetVolume 获取计算机上的存储区域
GetMemoryInfos 获取内存相关数据,如使用率等
GetLocalTime 获取计算机本地时间
GetSessionProcess 获取登录会话与该会话关联的进程之间的关联
GetSystemAccount 获取Windows系统账户
GetUserAccount 获取Windows系统上的用户账户信息
GetStartupCommand 获取当用户登录到计算机时自动运行的命令
GetUserInDomain 获取关联用户账户和 Windows NT 域
GetNTLogEvent 获取Windows事件
GetNTEventLogFile 获取存储在Windows事件日志中的数据
GetDiskPartition 获取运行Windows的计算机系统上物理磁盘分区区域的功能和管理容量
GetDiskUsage 获取所有分区使用情况
GetLogicalProgramGroup 获取运行Windows的计算机系统中的程序组
GetLogicalProgramGroupDirectory 将逻辑程序组 (分组关联到"开始"菜单) 中,以及存储它们的文件目录
GetLogicalProgramGroupItem 表示 由Win32_ProgramGroup 实例包含的元素,该元素本身不是另一个 Win32_ProgramGroup 实例
GetLogicalProgramGroupItemDataFile 将"开始"菜单的程序组项及其存储在其中的文件关联
GetProgramGroupContents 关联程序组顺序和包含的单个程序组或项
GetProgramGroupOrItem 获取用户"开始"菜单

3. sysinfos源代码

以下可单独存为psm1模块:

<#
@Auth: Jack Lee;
@Email: 291148484@163.com;
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#>
class sysinfos {
    static [object]GetServiceInfos() {
        <# Get the related data of the specified service. #>
        $services = Get-WmiObject -Class Win32_Service
        $service_info=@{}
        foreach ($i in $services) {
            $ServiceName = $i.Name
            if($ServiceName -ne $null){
                $service_info[$ServiceName] =  @{};
                $service_info[$ServiceName]["ExitCode"] = $i.ExitCode;
                $service_info[$ServiceName]["ProcessID"] = $i.ProcessID;
                $service_info[$ServiceName]["StartMode"] = $i.StartMode;
                $service_info[$ServiceName]["State"] = $i.State;
                $service_info[$ServiceName]["Status"] = $i.Status;
            }
        }
        return $service_info
    }
    # (GetServiceInfos)["JBoss"] | ConvertTo-Json
    static [object]IP4RouteTable(){
        <# Information that controls the routing of network packets #>
        return Get-WmiObject -Class Win32_IP4RouteTable
    }
    static [object]GetProcessInfos() {
        <# Get the relevant data of all processes #>
        $process = Get-WmiObject -Class Win32_Process;
        $process_info=@{};
        foreach ($i in $process) {
            $ProcessName = $i.Name
            if($ProcessName -ne $null){
                $process_info[$ProcessName] = @{};
                $process_info[$ProcessName]["Path"] = $i.Path; 
                $process_info[$ProcessName]["ExecutablePath"] = $i.ExecutablePath; 
                $process_info[$ProcessName]["Description"] = $i.Description;
                $process_info[$ProcessName]["CreationDate"] = $i.CreationDate;
                $process_info[$ProcessName]["InstallDate"] = $i.InstallDate;
                $process_info[$ProcessName]["TerminationDate"] = $i.TerminationDate;
                $process_info[$ProcessName]["UserModeTime"] = $i.UserModeTime;
                $process_info[$ProcessName]["Prioroty"] = $i.Prioroty;
                $process_info[$ProcessName]["Status"] = $i.Status;
                $process_info[$ProcessName]["SessionID"] = $i.SessionID;
                $process_info[$ProcessName]["ThreadCount"] = $i.ThreadCount;
                $process_info[$ProcessName]["CSName"] = $i.CSName;
                $process_info[$ProcessName]["Handle"] = $i.Handle;
                $process_info[$ProcessName]["HandleCount"] = $i.HandleCount;
                $process_info[$ProcessName]["VirtualSize"] = $i.VirtualSize;
                $process_info[$ProcessName]["WorkSetSize"] = $i.WorkSetSize;
            }
        }
        return $process_info
    }
    static [object]GetSystemRunningTime() {
        <# Get the running time of the system #>
        return ([Environment]::TickCount /86400000).ToString().Substring(0,3)+" D"
    }
    static [object]GetCPULoad(){
        <# Get the utilization rate of each core of CUP #>
        return @((Get-WmiObject -Class Win32_processor).LoadPercentage)
    }
    static [object]GetThread(){
        <# Get execution thread #>
        return Get-WMIObject -Class Win32_Thread
    }
    static [object]GetNetAdapter(){
        <# This method is used to obtain network adapter information on systems before WinServer2012/Win8.1, because Get-NetAdater is not available in these systems. #>
        return Get-WmiObject -Class Win32_NetworkAdapter
    }
    # GetNetAdapter  | ConvertTo-Json
    static [string]GetIpAddress(){
        $items = @{}
        $Name = "_?"
        foreach ($i in (ipconfig|findstr ":")) {
            if ($i.Split(":")[1] -eq ""){
                $Name = ($i.Split(":")[0]).Replace(" ","_")
                $items[$Name] = @{}
            }
            else{
                if($i.Contains("DNS")){
                    $items[$Name]["DNS Suffix"] = ($i.Split(": ")[1].Replace(" ",""))
                }
                if($i.Contains("IPv4")){
                    $items[$Name]["IPv4"] = ($i.Split(":")[1].Replace(" ",""))
                }
                if($i.Contains("IPv6")){
                    $items[$Name]["IPv6"] = ($i.Split(": ")[1].Replace(" ",""))
                }
            }
        }
        return $items
    }
    static [object]GetNetAdapterByDeviceID([int]$DeviceID){
        return Get-WMIObject -class Win32_NetworkAdapter -Filter DeviceID=$DeviceID
    }
    static [object]GetNetAdapterByName([string]$Name){
        return Get-WMIObject -class Win32_NetworkAdapter -Filter Name=$Name
    }
    static [object]GetNetAdapterByMACAddress([string]$MACAddress){
        return Get-WMIObject -class Win32_NetworkAdapter -Filter MACAddress=$MACAddress
    }
    static [object]GetVolume(){
        <# Get the storage area on the computer #>
        return Get-WmiObject -Class Win32_Volume
    }
    static [object]GetMemoryInfos(){
        $PhysicalMemory = Get-WmiObject -Class Win32_PhysicalMemory
        $free_total = ([math]::round(((Get-WmiObject -Class Win32_OperatingSystem).FreePhysicalMemory / (1mb)), 2))
        $Speed = @($PhysicalMemory.Speed);
        $Speed_Average = [math]::round((($PhysicalMemory.Capacity | Measure-Object -Average).Average /1000000),1)
        $capacity_total = [math]::round((($PhysicalMemory.Capacity | Measure-Object -Sum).Sum /1gb))
        return @{
            Capacitys = $PhysicalMemory.Capacity;
            Speeds=$Speed;
            Speed_Average = $Speed_Average
            Capacity_total = $capacity_total.ToString()+' Gb';
            Free_total = $free_total.ToString()+' Gb';
            Usage_Rate = ([math]::round(($capacity_total-$free_total)/$capacity_total, 2)).ToString() + '%'
        }
    }
    static [object]GetLocalTime(){
        <# This method is used to obtain the local time of the computer #>
        return Get-WmiObject -Class Win32_LocalTime
    }
    static [object]GetSessionProcess(){
        <# Get the association between the login session and the process associated with the session #>
        return Get-WmiObject -Class Win32_SessionProcess
    }
    static [object]GetSystemAccount(){
        <# Get Windows system account #>
        return Get-WmiObject -Class Win32_SystemAccount
    }
    static [object]GetUserAccount(){
        <# Get user account information on Windows system #>
        return Get-WmiObject -Class Win32_UserAccount
    }
    static [object]GetStartupCommand(){
        <# Get the command that runs automatically when the user logs in to the computer #>
        return Get-WmiObject -Class Win32_StartupCommand
    }
    static [object]GetUserInDomain(){
        <# Get associated user account and Windows NT domain #>
        return Get-WmiObject -Class Win32_UserInDomain
    }
    static [object]GetNTLogEvent(){
        <# Get Windows events #>
        return Get-WmiObject -Class Win32_NTLogEvent
    }
    static [object]GetNTEventLogFile(){
        <# Get the data stored in the windows event log #>
        return Get-WmiObject -Class Win32_NTEventLogFile
    }
    static [object]GetDiskPartition(){
        <# Get the function and management capacity of the physical disk partition area on the computer system running Windows. #>
        return Get-WmiObject -Class Win32_DiskPartition
    }
    static [object]GetDiskUsage() {
        <# Get all partition usage #>
        $logicaldisk = Get-WmiObject -Class Win32_Logicaldisk
        $disk_info=@{}
        foreach ($i in $logicaldisk) {
            $DeviceID = ($i.DeviceID).ToString();
            if($DeviceID -ne $null){
                $disk_info[$DeviceID] = @{}
                if(($i.Size -ne 0) -and  ($i.Size -ne $null)){
                    $disk_info[$DeviceID]['Total'] = ($i.Size/1073741824).ToString().Substring(0,5)+"Gb";
                    $disk_info[$DeviceID]['Free'] = ($i.FreeSpace/1073741824).ToString().Substring(0,5)+"Gb";
                    $disk_info[$DeviceID]['Usage'] = ((($i.Size-$i.FreeSpace) / $i.Size)*100).ToString().Substring(0,5)+"%"
                }else{
                    $disk_info[$DeviceID]['Total'] = $null
                    $disk_info[$DeviceID]['Free'] = $null
                    $disk_info[$DeviceID]['Usage'] = $null
                }
            }  
        }
        return $disk_info
    }
    # start menu
    static [object]GetLogicalProgramGroup(){
        <# Get the program group in the computer system running Windows #>
        return Get-WmiObject -Class Win32_LogicalProgramGroup
    }
    static [object]GetLogicalProgramGroupDirectory(){
        <# Associating logical program groups (grouping them into the Start menu) and the file directory where they are stored #>
        return Get-WmiObject -Class Win32_LogicalProgramGroupDirectory
    }
    static [object]GetLogicalProgramGroupItem(){
        <# Represents an element contained by a Win32_ProgramGroup instance, which is not another Win32_ProgramGroup instance #>
        return Get-WmiObject -Class Win32_LogicalProgramGroupItem
    }
    static [object]GetLogicalProgramGroupItemDataFile(){
        <# Associates the program group items in the Start menu with the files stored in them #>
        return Get-WmiObject -Class Win32_LogicalProgramGroupItemDataFile
    }
    static [object]GetProgramGroupContents(){
        <# Associates the sequence of program groups and the contained individual program groups or items #>
        return Get-WmiObject -Class Win32_ProgramGroupContents
    }
    static [object]GetProgramGroupOrItem(){
        <# Get the logical grouping of programs on the user's Start menu |Programs menu #>
        return et-WmiObject -Class Win32_ProgramGroupOrItem
    }
}


目录
相关文章
|
5天前
|
存储 运维 Ubuntu
自动化运维:使用Ansible管理服务器
【8月更文挑战第61天】本文将介绍如何使用Ansible工具进行服务器的自动化管理。我们将从基础概念开始,逐步深入到实际的应用案例,最后通过代码示例展示如何实现自动化部署和配置管理。无论你是初学者还是有经验的运维工程师,这篇文章都会为你提供有价值的参考。
|
14天前
|
运维 Ubuntu 应用服务中间件
自动化运维:使用Ansible进行服务器配置管理
【9月更文挑战第20天】在当今快速发展的信息技术时代,自动化运维已成为提升工作效率、减少人为错误的关键技术手段。本文将引导读者了解如何使用Ansible这一强大的自动化工具来简化和加速服务器的配置管理工作。通过实际代码示例,我们将一起探索Ansible的核心概念、基本操作以及如何构建可重复使用的Playbooks,旨在为读者提供一种清晰、高效的服务器管理方法。无论你是运维新手还是希望提高现有工作流程的效率,这篇文章都将为你提供宝贵的指导和启发。
|
7天前
|
存储 关系型数据库 MySQL
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
49 5
|
8天前
|
运维 监控 应用服务中间件
自动化运维:使用Ansible管理服务器
【9月更文挑战第26天】在这篇文章中,我们将探索如何使用Ansible来自动化运维任务。Ansible是一种简单而强大的自动化工具,可以简化服务器管理和配置过程。通过学习Ansible的基础知识和实践应用,您将能够更高效地管理您的服务器,并减少人为错误。无论您是初学者还是有经验的系统管理员,这篇文章都将为您提供宝贵的见解和实用的技巧。让我们一起开始学习如何利用Ansible来提升您的运维效率吧!
21 4
|
6天前
|
存储 运维 监控
服务器高效运维管理方案
智能运维作为保障业务连续性和提升系统性能的关键环节,其重要性日益凸显。服务器作为承载各类应用与数据的核心基础设施,其稳定性、安全性和性能直接关系到企业的业务运行效率和用户体验
17 1
|
25天前
|
存储 弹性计算 运维
自动化监控和响应ECS系统事件
阿里云提供的ECS系统事件用于记录云资源信息,如实例启停、到期通知等。为实现自动化运维,如故障处理与动态调度,可使用云助手插件`ecs-tool-event`。该插件定时获取并转化ECS事件为日志存储,便于监控与响应,无需额外开发,适用于大规模集群管理。详情及示例可见链接文档。
|
15天前
|
人工智能 运维 安全
专访浪潮信息:AI 原生时代,浪潮信息引领服务器操作系统创新 全面贡献龙蜥社区
分享了关于 AI 原生化趋势下服务器操作系统进化的思考,以及浪潮信息在龙蜥社区开源贡献的思路、成果与未来技术发展规划。
专访浪潮信息:AI 原生时代,浪潮信息引领服务器操作系统创新 全面贡献龙蜥社区
|
21天前
|
运维 应用服务中间件 网络安全
自动化运维:使用Ansible进行服务器配置管理
【9月更文挑战第13天】在IT运维领域,自动化工具的应用日益成为提升效率、降低错误率的关键。本文将介绍如何使用Ansible这一流行的自动化工具来简化和加速服务器的配置管理工作,通过实际案例展示其应用,并分享一些最佳实践。文章旨在帮助读者理解Ansible的核心概念,掌握基本使用方法,并鼓励大家探索更多可能的应用场景。
35 2
|
21天前
|
运维 应用服务中间件 网络安全
自动化运维的魔法:使用Ansible进行服务器配置管理
【9月更文挑战第13天】在这篇文章中,我们深入探讨如何利用Ansible这一强大的自动化工具来简化和加速你的服务器配置管理工作。我们将从基础概念出发,逐步引导你了解如何使用Ansible编写Playbooks,实现对服务器群的快速部署、配置更新与维护任务。通过实际案例,你将看到Ansible如何节省时间、减少人为错误并提高运维效率。无论你是初学者还是有经验的运维工程师,这篇文章都将带给你新的视角和启发。
|
23天前
|
存储 运维 网络协议
运维的基本概念:服务器和网络基础知识
运维的基本概念:服务器和网络基础知识
44 0
运维的基本概念:服务器和网络基础知识
下一篇
无影云桌面