Access SQL - WMI Namespaces from Remote Machine - sql

i am playing with Powershell and SQL WMI events and i am wondering if i can do this stuff remotely from the admin notebook:
I'd like to query the "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" namespace:
On SQLServer directly:
get-wmiobject -list -namespace "root\Microsoft\SqlServer" >> Works!
get-wmiobject -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" >> Works !
On my Adminmachine:
get-wmiobject -list -namespace "root\Microsoft\SqlServer" >> Works!
get-wmiobject -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER" >> Error: Invalid Namespace.
Is there a trick to get this running? Do i have to additional install sth?
I am still on SQL 2005.
Thanks!

Use the computername name parameter.
get-wmiobject -computername Z002 -list -namespace "root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER"
Also keep in mind MSSQLSERVER is only available if the server has a default instance. If the server uses a named instance you'll need to specify the instance name instead of MSSQLSERVER.

Posted - 05/05/2012 : 08:25:20
Hi All,
We've developed a free WMI CLR assembly to execute WMI queries in SQL.
e.g. This will return mount point and drive space
DECLARE #XmlData Xml
--Obtain Windows Services
select #XmlData=dbo.GetWMI('\\SQL2008WIN2008\root\cimv2', --Machine and WMI class
NULL, --UserName, leave NULL to use current
NULL, --Password, leave NULL to use current
'select * from win32_volume' --WMI Class
)
SELECT
tbl.A.value('(DeviceID)[1]','VARCHAR(100)') as DeviceID,
tbl.A.value('(Name)[1]','VARCHAR(200)') as Name,
tbl.A.value('(DriveType)[1]','int') as DriveType,
ISNULL(tbl.A.value('(DriveLetter)[1]','VARCHAR(10)'),'MountPoint') as DriveLetter,
tbl.A.value('(FreeSpace)[1]','bigint')/1024/1024 as FreeSpaceMbytes
FROM #XmlData.nodes('/WMI/Data') tbl(A)
Have a look at http://micatio.com/sqlwmi.aspx

Related

Setup Alert when SQL Agent Down using Task Scheduler

I am looking something to setup alert notification when SQL agent is down, sometimes when windows patch apply or server get rebooted SQL Agent is not restarting even though we have set up SQL Agent properties Auto Restart SQL Server if it stops unexpectedly
Auto Restart SQL Server Agent if it stops unexpectedly.
I have also tried to setup services on Component service on server to at Recovery tab, First Failure Restart the service and also restarted service rebooted but didn't work.
Is it any way I can get the alert so I can restart service manually when it's Agent is down it it will trigger to restart the job when Agent it's down.
$AgentStatus = (Get-Service -ComputerName <CompName> -Name <SqlServerAgentName> | Where-Object {$_.Status -eq "Stopped"} | Measure-Object).Count
If($AgentStatus -eq 1){
Start-Service -Name SqlServerAgentName
$SMPTPort = <Specify port number>
$From = "email1#domain.com"
$To = "email2#domain.com"
$Subject = "The SQL Server Agent Service in $env:ComputerName has been restarted."
$Body = "The SQL Server Agent Service <SqlServerAgentName> was in a Stopped state and has been restarted."
$SMTPServer = "SMTP SERVER"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, $SMPTPort)
$SMTPClient.EnableSsl = $false
$SMTPClient.Send($From, $To, $Subject, $Body)}
You can try creating a batch file below which checks for service status. This sends an SMTP mail (using powershell) along with restarting service again.
for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
powershell -ExecutionPolicy ByPass -Command Send-MailMessage -SmtpServer SMTPSERVER -To someone#domain.com -From noreply#domain.com -Subject Testing -Body Service_Not_Running
net start "MyServiceName"
)
)
Once you have the script ready, create a task scheduler to call the batch file. Run the scheduler every 1 hr or so.

Network error on powershell SQL job step

This is partially my code and partially from others help here on stack overflow.
$excelFile = "C:\ExcelTest\Test.csv"
$functionDirectory = "C:\foldername"
$csv = Import-csv $excelFile -Header FileName
Import-Module sqlps
foreach ($line in $csv)
{
if(test-path -path ($functionDirectory + "\" + $line.FileName))
{
invoke-sqlcmd -inputfile "C:\foldername\filename.sql" -serverinstance "servername\instancename" -database "databasename"
}
}
I had to remove the specific serverinstance / servername for privacy but I've checked both of those several times and I don't think that is where the issue is. I keep getting the error
A network related or instance specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections.
I have double checked server / instance name which I got from the server by running
select ##servername + '\' + ##SERVICENAME
nd the database name obviously was easy to get. I have double checked that the server is set up for remote connection (even though this is a database that is local on my laptop and not a remote server currently).
I'm kinda at a loss for what else to check for.
I had read you should look at firewall settings but I don't think those should make a difference when its a local server on my machine.
I'm still somewhat new with SQL and powershell so I apologize for any blatant syntax or formatting errors (please point out so I can correct them). Any help would be appreciated.
Turns out I needed to remove the instance name and just use the server name.

AZUR - Export Using BCP with Query

I want to export data from a database Azur to an Excel file.
To do this, i use the command :
bcp [DatabaseName].[Table] OUT C:...\Test_Export.xls -c -U UserName#ServerName.database.windows.net -S tcp:ServerName.database.windows.net -P xxxxxxxx
--> It Works
BUT, when i want do the same with SQL Query in the command, like this :
bcp "Select field1, Field2 FROM [dbo].[ForecastTrialDisag]" QUERYOUT C:..\Test_Export.xls -d [DataBaseName] -c -U UserName#ServerName.database.windows.net -S tcp:ServerName.database.windows.net -P xxxxxx
I have errors :
SQLState = 37000, NativeError = 4060
Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Cannot open database
"[DataBaseName]" requested by the login. The login failed.
SQLState = 28000, NativeError = 18456
Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Login failed for user 'UserName'.
I don't understand why it doesn't work with a SQL query. UserName, databaseName and password are OK.
Thank you for your help,
Simon
I believe the username is in the format of: "user#server" without the "databases.windows.net" part at the end.
Have you tried that?
If the password is a strong one - contains punctuation for example, in my case I had a * and and ^ character in the password - than the use of double quotes for the password is needed:
bcp "Select field1, Field2 FROM [dbo].[ForecastTrialDisag]" QUERYOUT C:..\Test_Export.xls -d [DataBaseName] -c -U UserName#ServerName.database.windows.net -S tcp:ServerName.database.windows.net -P "xxxxxx"
I struggled with this for some hours by using the main db admin user define in Azure and never got it to work - I'm sure I was missing something simple.
What got me over the hump was to use SQL and CREATE USER plus GRANT a user inside of SQL, the kind of user that's not apparently visible in the Azure portal but is easily visible inside of SQL Management Studio.
This worked super well for me.

Call WCF Service from bat file

is it possible to call a Methode of a WCF Service in a bat file. We want to test if the WCF Service works correct after the Server was restartet.
There are no commands within the BAT file universe that will allow you to contact a WCF service directly, however you could use a BAT file to run an existing console program that can connect and interact with a WCF service. So the answer is both yes and no; not directly, but through a separate program yes.
If you need some simple, clickable way of accessing a WCF service, I'd go with a Powershell or VB script (assuming you're in a windows environment).
Maybe you will be able to use PowerShell? It would be easier then. Create script with content:
$url = 'http://yoursite.url/example.svc'
$action = "`"http://some.namespace/method`""
$SOAPRequest = [xml]#'heregoesxmlmessage'#
write-host "Sending SOAP Request To Server: $url"
$soapWebRequest = [System.Net.WebRequest]::Create($url)
$soapWebRequest.Headers.Add("SOAPAction", $action)
$soapWebRequest.ContentType = "text/xml;charset=`"utf-8`""
$soapWebRequest.Accept = "text/xml"
$soapWebRequest.Method = "POST"
write-host "Initiating Send."
$requestStream = $soapWebRequest.GetRequestStream()
$SOAPRequest.Save($requestStream)
$requestStream.Close()
write-host "Send Complete, Waiting For Response."
$resp = $soapWebRequest.GetResponse()
$responseStream = $resp.GetResponseStream()
$soapReader = [System.IO.StreamReader]($responseStream)
$ReturnXml = [Xml] $soapReader.ReadToEnd()
$responseStream.Close()
write-host "Response Received."
$ReturnXml.OuterXml | out-file ".\test.xml"
write-host $ReturnXml.OuterXml
As mentioned in the other answers Powershell is probably the best way to go using the New-WebServiceProxy cmdlet.
http://technet.microsoft.com/library/hh849841.aspx
Example from the link above:
PS C:\> $URI = "http://www.webservicex.net/uszip.asmx?WSDL"
PS C:\>$zip = New-WebServiceProxy -Uri $URI -Namespace WebServiceProxy -Class USZip
PS C:\> $zip.getinfobyzip(20500).table
CITY : Washington
STATE : DC
ZIP : 20500
AREA_CODE : 202
TIME_ZONE : E

Creating IIS7 web application using PowerShell with Require SSL set to "Require"

I'm creating an IIS web site using PowerShell's New-WebSite cmdlet, and within that a web application using New-WebApplication.
The SSL settings for the web application need to be set to Require SSL; Require as shown below.
For consistency, I would like to do this using only PowerShell cmdlets.
The Require SSL setting is easy; you just add the -Ssl parameter to New-Website.
However, the only way we've found to set the Require option is using Appcmd.exe:
& $env:SystemRoot\System32\inetsrv\Appcmd.exe `
set config "$WebSiteName/$VirtualDirName" `
/section:access `
/sslFlags:"SslRequireCert" `
/commit:APPHOST
Is there a PowerShell alternative to this?
I had to add ssl to the value:
Set-WebConfiguration -Location "$WebSiteName/$WebApplicationName"
-Filter 'system.webserver/security/access'
-Value "Ssl, SslRequireCert"
Solution found, using Set-WebConfiguration:
Set-WebConfiguration -Location "$WebSiteName/$WebApplicationName" `
-Filter 'system.webserver/security/access' `
-Value "SslRequireCert"
I used this method:
Set-WebConfigurationProperty -PSPath "machine/webroot/apphost" `
-location "$mySiteName" -filter "system.webserver/security/access" `
-name "sslflags" -value "Ssl,SslNegotiateCert,SslRequireCert"
If you get the error "There is no configuration defined for object at path IIS:\SslBindings" you need to set the PsPath parameter
-PSPath IIS:\Sites