I can easily read the SQL Error Logs using the below code but cannot find a way to read the Agent Error Logs. Does anyone know if it is possible?
$sqlServer = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
$sqlServer.ReadErrorLog()
I've searched through the namespaces and there isn't anything obvious pointing me to the logs. I have tried this without success.
$sqlAgent = new-object ("Microsoft.SqlServer.Management.Smo.Agent") $server
$sqlAgent.ReadErrorLog()
#Pondlife was correct. For anyone else facing this problem, this worked for my purposes.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$sqlServer = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
$jobServer = $sqlServer.JobServer;
$jobServer.ReadErrorLog() |
where { ($_.ErrorLevel -lt 3) -and ($_.LogDate -ge $(Get-Date).AddDays($EventLogDaysToReview)) } |
Format-Table -AutoSize -wrap
Related
I've been trying to create a powershell script to automate something in my router's website but I can't really navigate through the sites frames and framesets, any help would be greatly appreciated!
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true # Make it visible
$ie.Navigate("http://192.168.1.1")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $ie.document.getElementByID('userName')
$usernamefield.value = "admin"
$passwordfield = $ie.document.getElementByID('pcPassword')
$passwordfield.value = "admin"
$Link = $ie.document.getElementByID('loginBtn')
$Link.click()
$Frame1a = $ie.document.getElementByID("topFrame")
$Frame2a = $Frame1a.contentWindow
$Frame3a = $Frame2a.document
$Frame1b = $Frame3a.getElementByID('bottomLeftFrame')
$Frame2b = $Frame1b.contentWindow
$Frame3b = $Frame2b.document
$thing = $Frame3b.getElementsByTagName('a') | where-object {$_.innerText -eq 'Wireless'}
This is the code I have so far, but when it gets to $Frame1b = $Frame3a.getElementByID('bottomLeftFrame') I get an error message saying: "You cannot call a method on a null-valued expression."
After I get this frame thing to work, I'd need it to click a hyperlink, if anyone knows how to do that please tell me, I've tried before but it didn't work. I've also tried different languages before, python, VBS, but I got the furthest with powershell.
Thanks for the attention!
I had similar issue in the past. I solved it like this:
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true # Make it visible
$ie.Navigate("http://192.168.1.1")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $ie.document.getElementByID('userName')
$usernamefield.value = "admin"
$passwordfield = $ie.document.getElementByID('pcPassword')
$passwordfield.value = "admin"
$Link = $ie.document.getElementByID('loginBtn')
$Link.click()
start-Sleep -Milliseconds 500
#Click Wireless
$oFrameLeft=$ie.document.parentwindow.frames['bottomLeftFrame'].document
$oWireless = $oFrameLeft.IHTMLDocument3_getElementsByTagName('a') | where-object {$_.innerText -eq 'Wireless'}
$oWireless.click()
I am working on a powershell script that needs some input from a mySQL database. For the life of me I can't tell what I've done wrong here.
Every other time I run this script, I get an error Exception calling "Open" with "0" argument(s): "Out of sync with server"[0]. So, the first run, it will pull the expected data and dump it on my screen, then on the next run I get that error. And the cycle just repeats. Here is my full code (right now its just a test query to pull then dump the data. If it matters, the mySQL server is running MariaDB 10.3.14 on a Ubuntu 18.04 host.
$error.Clear()
$sqlQuery = get-content -path "C:\querytext.sql" -Raw
$sqlUser = "myuser"
$sqlPass = "mypass"
$sqlHost = "myserver"
$sqlDB = "dbname"
$connectionString = "server= $sqlHost;port=3306;uid=$sqlUser;pwd=$sqlPass;database=$sqlDB"
Try{
$connection = New-Object MySql.data.MySqlClient.MySqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = New-Object MySql.data.MySqlClient.MySqlCommand($sqlQuery,$connection)
$dataAdapter = New-Object MySql.data.MySqlClient.MySqlDataAdapter($command)
$dataSet = New-Object System.Data.DataSet
$dataAdapter.fill($dataSet, "data") | Out-Null
$command.Dispose()
$sqlResults = $dataSet.tables["data"]
}
Catch {
Write-Host "ERROR : Unable to run query : $query `n$Error[0]"
}
$connection.close()
$sqlResults | Format-Table
$sqlResults | ForEach-Object {
write-host $_.fname
}
Might I suggest using the SQL PS module:
https://learn.microsoft.com/en-us/sql/powershell/download-sql-server-ps-module?view=sql-server-2017
That page has installation instructions and its from Microsoft. Personally, the dotnet class you are using, it works, but its relatively difficult to work with.
Connecting to a DB is much simpler with this module and you do not have to worry about micromanaging connections.
Invoke-Sqlcmd -ServerInstance $sqlHost -Query $sqlQuery -Database $sqlDB -Username $sqlUser -Password $sqlPass
This will return a PS object like every other PS cmdlet.
I am writing a script to ultimately check a block of servers for a certificate by FriendlyName and then go back and delete them once confirmed. Right now I am just trying to get the initial check to work. Currently it is not returning any data. Can anyone help?
$ContentsPath = "C:\Servers.txt"
$Servers = Get-Content $ContentsPath
$CertDeletionFile = "C:\CertsDeleted.csv"
$Today = Get-Date
$Certificate = Read-Host -Prompt "What certificate would you like to
REMOVE?"
write-host $Certificate
function findCert {
param ([string]$Certificate)
Invoke-Command -ComputerName $Servers -ScriptBlock {Get-Childitem -Path
Cert:LocalMachine\My | where {$_.friendlyname -eq $Certificate } | Select-
Object -Property FriendlyName }
}
findCert
As Mathias R. Jessen comments, your findcert function needs a certificate name as a parameter, and you aren't passing anything when you call it, so it won't run properly.
You're also trying to use a local computer variable $Certificate, on a remote computer inside an invoke-command, and the remote computer can't get to that variable across the remoting.
I've rewritten it, with $using: which is a syntax that tells PS to send the value over the remoting session, and with renamed variables so it's more clear which part is accessing which variables:
$ContentsPath = 'C:\Servers.txt'
$Servers = Get-Content -LiteralPath $ContentsPath
$CertDeletionFile = 'C:\CertsDeleted.csv'
$Today = Get-Date
$typedCertificateName = Read-Host -Prompt "What certificate would you like to
REMOVE?"
write-host $typedCertificateName
function findCert {
param ([string]$Certificate)
Invoke-Command -ComputerName $Servers -ScriptBlock {
Get-Childitem -Path Cert:LocalMachine\My |
where-Object {$_.friendlyname -eq $using:Certificate } |
Select-Object -Property FriendlyName
}
}
findCert -Certificate $typedCertificateName
I have recently started my journey with Powershell. My IT manager thought it would be a good idea to give me projects to complete. I am understanding Powershell more and more but I have run into quite the road block and need some assistance. The ConvertTo-HTML at the end of my code works, as in I get the file I need in the specified directory. However, I cannot get data to show in the HTM file. Any suggestions? Again, this is my very first script I have attempted on my own.
$computers = Get-ADComputer -Filter {Name -like '[enternamehere]*'} | Select -Expand DNSHostName
foreach ($computer in $computers)
{
Invoke-Command -Computer $computer -scriptblock {
(Get-WmiObject -Class Win32_ComputerSystem -Property Name).Name
Get-ScheduledTask -TaskName *[entertasknamehere]* | Get-ScheduledTaskInfo
}
}
ConvertTo-Html | Out-file -FilePath "[enterfilepathhere]"
I am trying to test our a web page we built that has a temp ssl cert, the issue is that when I goto the page I get the IE security warning that the ssl cert is invalid, with two links one to close the page, and the other to proceed to the page. I was able to use powershell to open IE and click the link on the ssl warning page, but now I need to populate the username and password input boxes and then click the login button.
$url = "res://ieframe.dll/invalidcert.htm?SSLError=50331648#https://10.2.2.1:8050/showme.do"
$ie = New-Object -comobject InternetExplorer.Application
$ie.visible = $true
$ie.silent = $true
$ie.Navigate( $url )
while( $ie.busy){Start-Sleep 1}
$secLink = $ie.Document.getElementsByTagName('A') | Where-Object {$_.innerText - eq 'Continue to this website (not recommended).'}
$secLink.click()
$ie.Document.getElementsByType("input") | where { $.Name -eq "j_username" }.value = "user"
$ie.Document.getElementsByName("input") | where { $.Name -eq "j_password" }.value = "password"
$loginBtn = $ie.Document.getElementsById('input') | Where-Object {$_.Type -eq 'button' -and $_.Value -eq 'LoginButton'}
$loginBtn.click()
So right now the page opens but the input fields are not populated or the button clicked, Do I need some kind of loop or while statement?
thanks
You need to wait until the page finishes loading when you've clicked on a link.
$url = "res://ieframe.dll/invalidcert.htm?SSLError=50331648#https://10.2.2.1:8050/showme.do"
$ie = New-Object -comobject InternetExplorer.Application
$ie.visible = $true
$ie.silent = $true
$ie.Navigate( $url )
while( $ie.busy){Start-Sleep 1}
$secLink = $ie.Document.getElementsByTagName('A') | Where-Object {$_.innerText - eq 'Continue to this website (not recommended).'}
$secLink.click()
while( $ie.busy){Start-Sleep 1}
$ie.Document.getElementsByType("input") | where { $.Name -eq "j_username" }.value = "user"
$ie.Document.getElementsByName("input") | where { $.Name -eq "j_password" }.value = "password"
$loginBtn = $ie.Document.getElementsById('input') | Where-Object {$_.Type -eq 'button' -and $_.Value -eq 'LoginButton'}
$loginBtn.click()
Write-Output "- Kill all IE windows"
get-process iexplore | stop-process -Force
Start-Sleep -s 1
function that open IE for a given url and a password retrieved from encrypted file
function OpenIE([string]$url, [string]$p)
{
Open Internet Explorer with a given url
$wshell = New-Object -com WScript.Shell
$wshell.Run("iexplore.exe $url")
Start-Sleep 1
Send user credentials to IE
$wshell.sendkeys("+{TAB}")
$wshell.sendkeys("username")
$wshell.sendkeys("{TAB}")
$wshell.sendkeys($p)
$wshell.sendkeys("{ENTER}")
}
$credentialsfile = "C:\temp\credfile.txt"
Check if credential file exists
if (Test-Path $credentialsfile)
{
Retrieve the credentials from an encrypted file
$encp = get-content $credentialsfile | convertto-securestring
$ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($encp)
$p = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr)
remove-variable encp,ptr
}else{
Request credentials and save to encrypted file
$creds = Get-Credential –credential DOMAIN\user
$encp = $creds.password
$encp |ConvertFrom-SecureString |Set-Content $credentialsfile
}
Write-Output "- open IE"
OpenIE "http://www.yoururlhere.com" $p
You would probably find it a lot easier to work with something like the (free) Windows Automation module for PowerShell up on codeplex:
WASP is a PowerShell snapin for Windows Automation tasks like
selecting windows and controls and sending mouse and keyboard events.
We have automation cmdlets like Select-Window, Select-Control,
Send-Keys, Send-Click, Get-WindowPosition, Set-WindowPosition,
Set-WindowActive, Remove-Window ... etc.
Our goal is to enable you to accomplish most Windows GUI Automation
scripting from inside PowerShell, without resorting to specialized
(and expensive) scripting tools.
http://wasp.codeplex.com/