top of page

PowerShell SQL Update Script

4) The Update Script will take the report.txt file as input

to add the missing servers to the SQL database table. 

​

#=====================================================
# Get Service Information and Export \ Import CSV 
#=====================================================

#Get List of Servers from Report.txt
$GetNewServers = Get-Content C:\temp\Report.txt

#Query Each Server for a List of Running Services
$NewResults=Invoke-Command -ComputerName $GetNewServers -ScriptBlock {Get-Service | Where{$_.Status -eq "Running"}}

#Export & Import Select Results
$NewResults | Select PSComputerName,Name, DisplayName | Export-csv C:\temp\MyNewServices.csv -NoTypeInformation 
$NewImportData=Import-CSV C:\temp\MyNewServices.csv

#Popup to Assure you Want to Add to SQL
$ReturnValue=[System.Windows.MessageBox]::Show('Would you like to update SQL Table?','Game input','YesNo','Error')

If($ReturnValue -eq "Yes"){

    #=====================================
    # Insert New Data Into SQL DB Table 
    #=====================================

    #Downloads and Installs SQL Module and Will Overwrite and Older Version Module Installed
    Install-Module -Name SqlServer -AllowClobber

    #Loop Through Each Record and Add to SQL Table
    Foreach($Comp in $NewImportData){

        $insertquery="
                INSERT INTO [dbo].[ComputerServices]
                ([PSComputerName]
                ,[Name]
                ,[DisplayName])
         VALUES
               ('$($Comp.PSComputerName)'
               ,'$($Comp.Name)'
               ,'$($Comp.Displayname)')"

        #Command to Insert to SQL     
        Invoke-Sqlcmd -ServerInstance Desktop-Main -database ServerManager -Query $insertquery
    }
}

bottom of page