OpsaC - Operating as PowerShell code
published: March 13, 2021 author: Tinu tags: PowerShell categories: PowerShell-SQL
Create a new table with the rows LastRunTime, ComputerName, WUServer, LastPatchRun, LastPatchStatus, CumulativeUpdate, CumulativeUpdate and RestartHistory.
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [String] $SqlInstance = 'MySQLInstance',
    [Parameter(Mandatory=$true)]
    [String] $Database = 'MyDatabase',
    [Parameter(Mandatory=$true)]
    [String] $Table = 'MyTable'
)
Begin{
$SqlQuery = @"
USE $($Database);
GO
CREATE TABLE $($Table) (
  ID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
  LastRunTime datetime,
  ComputerName nvarchar(255) NOT NULL,
  WUServer nvarchar(255),
  LastPatchRun nvarchar(255),
  LastPatchStatus nvarchar(255),
  HotFix nvarchar(255),
  CumulativeUpdate nvarchar(255),
  RestartHistory nvarchar(255),
);
GO
"@
}
Process{
    if(-not($MySqlCredentials)){
        $MySqlCredentials = Get-Credential -Message "Enter the user to connect to $SqlInstance" -UserName "$($env:USERDNSDOMAIN)\$($env:USERNAME)"
    }
    try{
        $PSBoundParameters | Out-String | foreach {Write-Verbose $_}
        $StartDate = Get-Date
        $result    = Invoke-DbaQuery -SqlInstance $SqlInstance -SqlCredential $MySqlCredentials -Database $Database -Query $SqlQuery
    }
    catch{
        Write-Host "An error occured, details:" -ForegroundColor Red
        [PSCustomObject]@{
            Activity   = $($_.CategoryInfo).Activity
            Scriptname = $($_.InvocationInfo.ScriptName)
            LineNumber = $($_.InvocationInfo.ScriptLineNumber)
            Message    = $($_.Exception.Message)
            Category   = $($_.CategoryInfo).Category
            Exception  = $($_.Exception.GetType().FullName)
            TargetName = $($_.CategoryInfo).TargetName
        }        
        $Error.clear()
        $MySqlCredentials = $null
    }
    finally{
        $EndDate = Get-Date
        $TotalMS = "{0:N0}" -f (New-TimeSpan –Start $StartDate –End $EndDate | Select-Object -ExpandProperty MilliSeconds)
        Write-Host "[$($TotalMS)ms] Query return $($result.ID.count) rows" -ForegroundColor Green
    }
}
End{
    return $result
}
Delete the table WindowsPatching.
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [String] $SqlInstance = 'MySQLInstance',
    [Parameter(Mandatory=$true)]
    [String] $Database = 'MyDatabase',
    [Parameter(Mandatory=$true)]
    [String] $Table = 'MyTable'
)
Begin{
$SqlQuery = @"
USE $($Database);
GO
DROP TABLE $($Table);
GO
"@
}
Process{
    if(-not($MySqlCredentials)){
        $MySqlCredentials = Get-Credential -Message "Enter the user to connect to $SqlInstance" -UserName "$($env:USERDNSDOMAIN)\$($env:USERNAME)"
    }
    try{
        $PSBoundParameters | Out-String | foreach {Write-Verbose $_}
        $StartDate = Get-Date
        $result    = Invoke-DbaQuery -SqlInstance $SqlInstance -SqlCredential $MySqlCredentials -Database $Database -Query $SqlQuery
    }
    catch{
        Write-Host "An error occured, details:" -ForegroundColor Red
        [PSCustomObject]@{
            Activity   = $($_.CategoryInfo).Activity
            Scriptname = $($_.InvocationInfo.ScriptName)
            LineNumber = $($_.InvocationInfo.ScriptLineNumber)
            Message    = $($_.Exception.Message)
            Category   = $($_.CategoryInfo).Category
            Exception  = $($_.Exception.GetType().FullName)
            TargetName = $($_.CategoryInfo).TargetName
        }        
        $Error.clear()
        $MySqlCredentials = $null
    }
    finally{
        $EndDate = Get-Date
        $TotalMS = "{0:N0}" -f (New-TimeSpan –Start $StartDate –End $EndDate | Select-Object -ExpandProperty MilliSeconds)
        Write-Host "[$($TotalMS)ms] Query return $($result.ID.count) rows" -ForegroundColor Green
    }
}
End{
    return $result
}
Insert a new record with a ComputerName and the current TimeStamp..
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [String] $SqlInstance = 'MySQLInstance',
    [Parameter(Mandatory=$true)]
    [String] $Database = 'MyDatabase',
    [Parameter(Mandatory=$true)]
    [String] $ComputerName = 'MyComputer.domain.com',
    [Parameter(Mandatory=$true)]
    [String] $Table = 'MyTable'
)
Begin{
$SqlQuery = @"
USE $($Database);
GO
INSERT INTO $($Table) (ComputerName, LastRunTime)
VALUES ('$($ComputerName)',CURRENT_TIMESTAMP);
GO
"@
}
Process{
    if(-not($MySqlCredentials)){
        $MySqlCredentials = Get-Credential -Message "Enter the user to connect to $SqlInstance" -UserName "$($env:USERDNSDOMAIN)\$($env:USERNAME)"
    }
    try{
        $PSBoundParameters | Out-String | foreach {Write-Verbose $_}
        $StartDate = Get-Date
        $result    = Invoke-DbaQuery -SqlInstance $SqlInstance -SqlCredential $MySqlCredentials -Database $Database -Query $SqlQuery
    }
    catch{
        Write-Host "An error occured, details:" -ForegroundColor Red
        [PSCustomObject]@{
            Activity   = $($_.CategoryInfo).Activity
            Scriptname = $($_.InvocationInfo.ScriptName)
            LineNumber = $($_.InvocationInfo.ScriptLineNumber)
            Message    = $($_.Exception.Message)
            Category   = $($_.CategoryInfo).Category
            Exception  = $($_.Exception.GetType().FullName)
            TargetName = $($_.CategoryInfo).TargetName
        }        
        $Error.clear()
        $MySqlCredentials = $null
    }
    finally{
        $EndDate = Get-Date
        $TotalMS = "{0:N0}" -f (New-TimeSpan –Start $StartDate –End $EndDate | Select-Object -ExpandProperty MilliSeconds)
        Write-Host "[$($TotalMS)ms] Query return $($result.ID.count) rows" -ForegroundColor Green
    }
}
End{
    return $result
}
Update a record with ID 1 and insert a value in the field LastPatchRun.
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [String] $SqlInstance = 'MySQLInstance',
    [Parameter(Mandatory=$true)]
    [String] $Database = 'MyDatabase',
    [Parameter(Mandatory=$true)]
    [String] $Table = 'MyTable',
    [Parameter(Mandatory=$true)]
    [Int] $ID = 1,
    [Parameter(Mandatory=$true)]
    [String] $LastPatchRun = '2021.02.10 05:42:50'
)
Begin{
$SqlQuery = @"
USE $($Database);
GO
UPDATE $($Table)
SET LastPatchRun = $($LastPatchRun)
WHERE ID = $($ID);
GO
"@
}
Process{
    if(-not($MySqlCredentials)){
        $MySqlCredentials = Get-Credential -Message "Enter the user to connect to $SqlInstance" -UserName "$($env:USERDNSDOMAIN)\$($env:USERNAME)"
    }
    try{
        $PSBoundParameters | Out-String | foreach {Write-Verbose $_}
        $StartDate = Get-Date
        $result    = Invoke-DbaQuery -SqlInstance $SqlInstance -SqlCredential $MySqlCredentials -Database $Database -Query $SqlQuery
    }
    catch{
        Write-Host "An error occured, details:" -ForegroundColor Red
        [PSCustomObject]@{
            Activity   = $($_.CategoryInfo).Activity
            Scriptname = $($_.InvocationInfo.ScriptName)
            LineNumber = $($_.InvocationInfo.ScriptLineNumber)
            Message    = $($_.Exception.Message)
            Category   = $($_.CategoryInfo).Category
            Exception  = $($_.Exception.GetType().FullName)
            TargetName = $($_.CategoryInfo).TargetName
        }        
        $Error.clear()
        $MySqlCredentials = $null
    }
    finally{
        $EndDate = Get-Date
        $TotalMS = "{0:N0}" -f (New-TimeSpan –Start $StartDate –End $EndDate | Select-Object -ExpandProperty MilliSeconds)
        Write-Host "[$($TotalMS)ms] Query return $($result.ID.count) rows" -ForegroundColor Green
    }
}
End{
    return $result
}
Delete the record with ID 1.
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [String] $SqlInstance = 'MySQLInstance',
    [Parameter(Mandatory=$true)]
    [String] $Database = 'MyDatabase',
    [Parameter(Mandatory=$true)]
    [String] $Table = 'MyTable',
    [Parameter(Mandatory=$true)]
    [Int] $ID = 1,
)
Begin{
$SqlQuery = @"
USE $($Database);
GO
DELETE
FROM $($Table)
WHERE ID = $($ID);
GO
"@
}
Process{
    if(-not($MySqlCredentials)){
        $MySqlCredentials = Get-Credential -Message "Enter the user to connect to $SqlInstance" -UserName "$($env:USERDNSDOMAIN)\$($env:USERNAME)"
    }
    try{
        $PSBoundParameters | Out-String | foreach {Write-Verbose $_}
        $StartDate = Get-Date
        $result    = Invoke-DbaQuery -SqlInstance $SqlInstance -SqlCredential $MySqlCredentials -Database $Database -Query $SqlQuery
    }
    catch{
        Write-Host "An error occured, details:" -ForegroundColor Red
        [PSCustomObject]@{
            Activity   = $($_.CategoryInfo).Activity
            Scriptname = $($_.InvocationInfo.ScriptName)
            LineNumber = $($_.InvocationInfo.ScriptLineNumber)
            Message    = $($_.Exception.Message)
            Category   = $($_.CategoryInfo).Category
            Exception  = $($_.Exception.GetType().FullName)
            TargetName = $($_.CategoryInfo).TargetName
        }        
        $Error.clear()
        $MySqlCredentials = $null
    }
    finally{
        $EndDate = Get-Date
        $TotalMS = "{0:N0}" -f (New-TimeSpan –Start $StartDate –End $EndDate | Select-Object -ExpandProperty MilliSeconds)
        Write-Host "[$($TotalMS)ms] Query return $($result.ID.count) rows" -ForegroundColor Green
    }
}
End{
    return $result
}
Select the TOP 10 records.
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [String] $SqlInstance = 'MySQLInstance',
    [Parameter(Mandatory=$true)]
    [String] $Database = 'MyDatabase',
    [Parameter(Mandatory=$true)]
    [String] $Table = 'MyTable'
)
Begin{
$SqlQuery = @"
USE $($Database);
GO
SELECT TOP (10) * 
FROM [$($Database)].[dbo].[$($Table)];
GO
"@
}
Process{
    if(-not($MySqlCredentials)){
        $MySqlCredentials = Get-Credential -Message "Enter the user to connect to $SqlInstance" -UserName "$($env:USERDNSDOMAIN)\$($env:USERNAME)"
    }
    try{
        $PSBoundParameters | Out-String | foreach {Write-Verbose $_}
        $StartDate = Get-Date
        $result    = Invoke-DbaQuery -SqlInstance $SqlInstance -SqlCredential $MySqlCredentials -Database $Database -Query $SqlQuery
    }
    catch{
        Write-Host "An error occured, details:" -ForegroundColor Red
        [PSCustomObject]@{
            Activity   = $($_.CategoryInfo).Activity
            Scriptname = $($_.InvocationInfo.ScriptName)
            LineNumber = $($_.InvocationInfo.ScriptLineNumber)
            Message    = $($_.Exception.Message)
            Category   = $($_.CategoryInfo).Category
            Exception  = $($_.Exception.GetType().FullName)
            TargetName = $($_.CategoryInfo).TargetName
        }        
        $Error.clear()
        $MySqlCredentials = $null
    }
    finally{
        $EndDate = Get-Date
        $TotalMS = "{0:N0}" -f (New-TimeSpan –Start $StartDate –End $EndDate | Select-Object -ExpandProperty MilliSeconds)
        Write-Host "[$($TotalMS)ms] Query return $($result.ID.count) rows" -ForegroundColor Green
    }
}
End{
    return $result
}