草庐IT

sql-server - 1 Powershell 脚本 2 SQL 表

coder 2024-06-21 原文

我在 SQL Server Management Studio 中填充第二个表时遇到问题。 我的第一个表 ServerList 包含下面屏幕截图中的所有信息。第二个表 ServerDrives 应该包含有关硬盘规范的所有信息(免费、二手、盘符,以及硬盘连接到哪个服务器)。

目前,我的 powershell 脚本从 ServerList 中提取列 ServerName 中的所有值,并将信息推送到 powershell 脚本中,然后填充操作系统、RAM、等等

问题:我不确定如何让相同的 powershell 脚本使用来自表 ServerList 的相同主键 ServerID 来填充我的 ServerDrives表。因为我希望该表中的每一行都对应于 ServerList 中的每个服务器。我目前在脚本中有一种收集硬盘驱动器信息的方法,但我不确定如何使用该信息来填充我的空表


目标:让 ServerID(ServerList 中的主键)和 ServerDriveID(ServerDrives 中的主键)用于同一台服务器 (QAGGAPP01 、QAGGAPP03、QAGGAPP05 等)。将变量 $disks 推送到数据库表 ServerDrives 中,并使用正确的硬盘驱动器盘符和规范。每台服务器有 1 或 2 个硬盘驱动器。

代码:

    Write-Output " `n Start of Hal0 `n";

    #Start of Server Connection
    $connectionString = "Server=QAUTILITYDB01;Database=Hal0Test;Integrated Security=True;"
    $connection = New-Object System.Data.SqlClient.SqlConnection
    $connection.ConnectionString = $connectionString
    $connection.Open()
    $command = $connection.CreateCommand()

    $ServerArray = [System.Collections.ArrayList]@()
    $query = "SELECT ServerName FROM ServerList"
    $command.CommandText = $query
    $ServerNames = $command.ExecuteReader()

    $table = new-object “System.Data.DataTable”
    $table.Load($ServerNames)

    $ServerArray = $table | select -Expand ServerName

    $ServerArray | ForEach-Object {
        #$ServerArray returns each server name

        #Operating System
        $SystemInfo = Get-WmiObject -Class Win32_OperatingSystem -computername  $_
        $os = Get-WmiObject -Class Win32_OperatingSystem -Computer $_ 
        #Server's Memory (RAM) Usage Average
        $TotalRAM = [math]::round($SystemInfo.TotalVisibleMemorySize/1MB,4)
        $FreeRAM =  [math]::round($SystemInfo.FreePhysicalMemory/1MB,3)
        $UsedRAM = $TotalRAM - $FreeRAM
        $RAMPercentFree = [math]::round(($FreeRAM / $TotalRAM) * 100,3)
        $RAMPercentUsed = [math]::round(($UsedRAM / $TotalRAM) * 100,3)
        #Server's CPU (Proccess) Usage Average
        $cpuAVG = Get-WmiObject -computername $_ win32_processor |     Measure-Object -property LoadPercentage -Average | Select Average 

        #Server's Hard Drives (MB) Free/Used
        $disks = Get-WmiObject -Class Win32_LogicalDisk -Computer $_ |
             Where-Object {$_.DriveType -eq 3} |
             ForEach-Object {
                 '{0} {1:D} MB Free/{2:D} MB Used' -f $_.DeviceID,
                     [int]($_.FreeSpace/1MB), [int]($_.Size/1MB)
             }

        #Value Types being pushed to Server
        $command.CommandText = "UPDATE ServerList SET FQDN = '$_',
        TotalRAM= '$TotalRAM' ,
        FreeRAM= '$FreeRAM' ,
        UsedRAM= '$UsedRAM' ,
        RAMPercentFree = '$RAMPercentFree' ,
        RAMPercentUsed= '$RAMPercentUsed' ,
        OS = '$($os.Caption)' WHERE ServerName LIKE '$($os.PSComputerName)%';"
        $result = $command.ExecuteNonQuery()
}

    Write-Output "`n End of Hal0";


服务器驱动器:


HTML 预览,我的 powershell 代码只是为了更容易查看推送到服务器的内容,而不必每次都重新打开表:

最佳答案

根据另一条评论中的建议获取 ServerID。您可以按如下方式更改代码:

  • 使用 "SELECT ServerID, ServerName FROM ServerList" 获取名称和 ID
  • 通过管道传输结果表并分别读取 $ServerName$ServerID
  • 在遍历磁盘以插入/更新 $ServerID 时使用此信息

实现:

#Start of Server Connection
$ConnectionString = "<CONNECTION>"
$Connection = New-Object System.Data.SqlClient.SqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = $Connection.CreateCommand()
# Selects server id and name and puts it into the table
$ServerInfoQuery = "SELECT ServerID, ServerName FROM ServerList"
$Command.CommandText = $ServerInfoQuery
$ServerInfoReader = $Command.ExecuteReader()
$ServerInfo = New-Object System.Data.DataTable
$ServerInfo.Load($ServerInfoReader)    
$ServerInfo | ForEach-Object {
    # Read Name and ID from table
    $ServerName = $_.ServerName
    $ServerID = $_.ServerID
    # Operating System
    $SystemInfo = Get-WmiObject -Class Win32_OperatingSystem -computername  $ServerName
    $os = Get-WmiObject -Class Win32_OperatingSystem -Computer $ServerName        
    $TotalRAM = [math]::round($SystemInfo.TotalVisibleMemorySize/1MB,4)
    $FreeRAM =  [math]::round($SystemInfo.FreePhysicalMemory/1MB,3)
    $UsedRAM = $TotalRAM - $FreeRAM
    $RAMPercentFree = [math]::round(($FreeRAM / $TotalRAM) * 100,3)
    $RAMPercentUsed = [math]::round(($UsedRAM / $TotalRAM) * 100,3)
    # Server's CPU (Proccess) Usage Average
    $cpuAVG = Get-WmiObject -computername $ServerName win32_processor | Measure-Object -property LoadPercentage -Average | Select Average         
    # Value Types being pushed to Server
    $Command.CommandText = "
        UPDATE 
            ServerList 
        SET 
            FQDN = '$ServerName',
            TotalRAM= '$TotalRAM',
            FreeRAM= '$FreeRAM',
            UsedRAM= '$UsedRAM',
            RAMPercentFree = '$RAMPercentFree',
            RAMPercentUsed= '$RAMPercentUsed',
            OS = '$($os.Caption)' 
        WHERE 
            ServerID = $ServerID"       
    $result = $Command.ExecuteNonQuery()

    # Server's Hard Drives (MB) Free/Used
    $disks = Get-WmiObject -Class Win32_LogicalDisk -Computer $ServerName | Where-Object {$_.DriveType -eq 3} | ForEach-Object {
        $DriveLetter = $_.DeviceID
        $DiskFree = [Math]::Round($_.FreeSpace/1MB, 0)        
        $DiskUsed = [Math]::Round($_.Size/1MB, 0)
        $Command.CommandText = "
            IF EXISTS (SELECT * FROM ServerDrives WHERE ServerID = '$ServerID' AND DriveLetter = '$DriveLetter')
            BEGIN
                UPDATE
                    ServerDrives
                SET
                    DriveLetter = '$DriveLetter',
                    DiskFree = '$DiskFree',
                    DiskUsed = '$DiskUsed',
                    ServerID = '$ServerID'
                WHERE
                    ServerID = '$ServerID' AND DriveLetter = '$DriveLetter' 
            END
            ELSE
            BEGIN
                INSERT INTO 
                    ServerDrives (DriveLetter, DiskFree, DiskUsed, ServerID) 
                VALUES 
                    ('$DriveLetter','$DiskFree','$DiskUsed', '$ServerID')
            END"
        $command.ExecuteNonQuery()
    }
}

关于sql-server - 1 Powershell 脚本 2 SQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31269860/

有关sql-server - 1 Powershell 脚本 2 SQL 表的更多相关文章

  1. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  2. ruby-on-rails - 独立 ruby​​ 脚本的配置文件 - 2

    我有一个在Linux服务器上运行的ruby​​脚本。它不使用rails或任何东西。它基本上是一个命令行ruby​​脚本,可以像这样传递参数:./ruby_script.rbarg1arg2如何将参数抽象到配置文件(例如yaml文件或其他文件)中?您能否举例说明如何做到这一点?提前谢谢你。 最佳答案 首先,您可以运行一个写入YAML配置文件的独立脚本:require"yaml"File.write("path_to_yaml_file",[arg1,arg2].to_yaml)然后,在您的应用中阅读它:require"yaml"arg

  3. postman——集合——执行集合——测试脚本——pm对象简单示例02 - 2

    //1.验证返回状态码是否是200pm.test("Statuscodeis200",function(){pm.response.to.have.status(200);});//2.验证返回body内是否含有某个值pm.test("Bodymatchesstring",function(){pm.expect(pm.response.text()).to.include("string_you_want_to_search");});//3.验证某个返回值是否是100pm.test("Yourtestname",function(){varjsonData=pm.response.json

  4. Hive SQL 五大经典面试题 - 2

    目录第1题连续问题分析:解法:第2题分组问题分析:解法:第3题间隔连续问题分析:解法:第4题打折日期交叉问题分析:解法:第5题同时在线问题分析:解法:第1题连续问题如下数据为蚂蚁森林中用户领取的减少碳排放量iddtlowcarbon10012021-12-1212310022021-12-124510012021-12-134310012021-12-134510012021-12-132310022021-12-144510012021-12-1423010022021-12-154510012021-12-1523.......找出连续3天及以上减少碳排放量在100以上的用户分析:遇到这类

  5. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  6. ruby - 确定 ruby​​ 脚本是否已经在运行 - 2

    有没有一种简单的方法可以判断ruby​​脚本是否已经在运行,然后适本地处理它?例如:我有一个名为really_long_script.rb的脚本。我让它每5分钟运行一次。当它运行时,我想看看之前运行的是否还在运行,然后停止第二个脚本的执行。有什么想法吗? 最佳答案 ps是一种非常糟糕的方法,并且可能会出现竞争条件。传统的Unix/Linux方法是将PID写入文件(通常在/var/run中)并在启动时检查该文件是否存在。例如pid文件位于/var/run/myscript.pid然后你会在运行程序之前检查它是否存在。有一些技巧可以避免

  7. ruby - ruby 脚本可以预编译成二进制文件吗? - 2

    我正在开发一个Ruby脚本,需要在没有Ruby解释器的情况下部署到系统上。它将需要在使用ELF格式的FreeBSD系统上运行。我知道有一个ruby​​2exe项目可以编译在Windows上运行的ruby​​脚本,但是在其他操作系统上这样做容易吗?甚至可能吗? 最佳答案 您是否检查过Rubinius或JRuby是否允许您预编译您的代码? 关于ruby-ruby脚本可以预编译成二进制文件吗?,我们在StackOverflow上找到一个类似的问题: https://

  8. sql - 在 Rails Console for PostgreSQL 的表中显示数据 - 2

    我找到了这样的东西:Rails:Howtolistdatabasetables/objectsusingtheRailsconsole?这一行没问题:ActiveRecord::Base.connection.tables并返回所有表但是ActiveRecord::Base.connection.table_structure("users")产生错误:ActiveRecord::Base.connection.table_structure("projects")我认为table_structure不是Postgres方法。如何列出Postgres数据库的Rails控制台中表中的所有

  9. ruby-on-rails - rails : uninitialized constant just happen on production server - 2

    我有一个放在lib/network中的类:moduleNetworkApiclassNetworkProxyendend然后在另一个类中,我引用了这个类:network_proxy=::NetworkApi::NetworkProxy.new(params)一切都在我的开发环境中正常运行,但是当我部署到服务器时,我在上面一行收到错误消息:NameError:uninitializedconstantNetworkApi::NetworkProxy我不知道为什么会出现这个奇怪的错误。请告诉我为什么。 最佳答案 请注意Rails5dis

  10. ruby-on-rails - Ruby 从 bash 脚本执行中捕获 stderr 输出 - 2

    我目前可以将stdout重定向到ruby​​/rails中的字符串变量,只需在bash中运行命令并将结果设置为我的字符串变量,如下所示。val=%x[#{cmd}]其中cmd是表示bash命令的字符串。但是,这仅捕获stdout,因为我想捕获stderr并将其设置为ruby​​中的字符串——有什么想法吗? 最佳答案 简单地重定向它:val=%x[#{cmd}2>&1]如果您只想从stderr捕获输出,请在将其复制到fd2后关闭stdout的文件描述符。val=%x[#{cmd}2>&1>/dev/null]

随机推荐