Composing a script in Powershell V3 - string

I would like to know how i can create a script using powershell v3 to obtain the names of all the SQL instances. for example Environment 23Dev would have two virtual boxes. ASNAV-DEVSQL-23
and ASNAV-DEVWEB-23. I want to return the info ASNVA-DEVSQL-23 all the way up to Environment 50?
Can anyone assist with this?
Regards,
Joe

here is an example that will list sql instance of SQLSERVER1 and SQLSERVER2 :
"SQLSERVER1","SQLSERVER2" | % {
invoke-command -computername $_ -scriptblock{
"SERVER $env:computername"
(get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
}
}

This one-liner will list all your local instances in the form of a PowerShell object:
[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() | Format-Table -Auto
Taken from: http://tangodude.wordpress.com/2014/02/07/list-local-sql-server-instances-with-powershell/
Edit:
This bit of code should work better than the previous one:
$Current = Get-Location;
Import-Module SQLPS -DisableNameChecking;
Set-Location $Current;
[Microsoft.SqlServer.Management.Smo.SmoApplication]::EnumAvailableSqlServers()
Edit:
This is using WMI to query the services on the target computer.
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null;
$MC = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer("COMPUTER_NAME_HERE");
foreach ($Instance in ($MC.Services | Where-Object { $_.Type -Eq "SqlServer" }))
{
Write-Host $Instance.Name;
}

Related

Is there any PowerShell command to get the details for all Azure VM's that JIT (Just in Times) is assigned or not?

I am working to JIT (Just in time). It should be enabled in all Azure Virtual Machines.
For that, I am retrieving the details to see how many VM's JIT is enabled or disabled.
Is there any script or command to get these details via PowerShell which gives details in Excel?
The command should be Get-AzJitNetworkAccessPolicy
# Sample from microsoft docs
Get-AzJitNetworkAccessPolicy
Id : /subscriptions/487bb485-b5b0-471e-9c0d-10717612f869/resourceGroups/myService1/providers/Microsoft.Security/locations/centralus/jitNetworkAccessPolicies/default
Name : default
Kind : Basic
VirtualMachines : {/subscriptions/487bb485-b5b0-471e-9c0d-10717612f869/resourceGroups/myService1/providers/Microsoft.Compute/virtualMachines/testService}
Requests : {Microsoft.Azure.Commands.Security.Models.JitNetworkAccessPolicies.PSSecurityJitNetworkAccessPolicyRequest}
ProvisioningState : Succeeded
It's part of the Az.Security Module.
The command will show you all Just in Time Policies and the assigned machines (VirtualMachines Property)
Together with Get-AzVM you can create a list of which don't have JIT enabled yet.
Something like this should do the trick:
Import-Module Az.Compute
Import-Module Az.Security
Connect-AzAccount -SubscriptionId "<Id>"
$AzJITPolicies = Get-AzJitNetworkAccessPolicy
$AzVMs = Get-AzVM
$ResultSet = #("VmName;JITEnabled")
foreach($AzVM in $AzVMS) {
# You probably need to filter the rules even further here.
$PolicyExists = $AzJITPolicies | Where-Object { $_.VirtualMachines | Where-Object { $_.Id -eq $AzVm.Id }}
$JITEnabled = $false
if($PolicyExists) {
$JITEnabled = $true
}
$ResultSet += ($AzVM.Name + ";" + $JITEnabled)
}
# export as csv => import in excel
$ResultSet -join "`r`n" | Out-File "c:\result.csv"

Powershell script to get all parent resources

Good day,
I am trying to figure out a way to get all the parent objects in my azure subcription to a csv from Azure.
By parent object, I am refering to objects like, VMs, Webapps, Kubernetes Clusters, ect. I want to strip away any data that is deemed illrevelant like Nics, PIPs, storage disks, ect. I am not super proficent in powershell. and I am not sure how to tackle this.
I have an azure workbook that I created that gives a good overview in a nice format, I would like to export the entire workbook for offline viewing but that doesn't seem to be possible.
Any help would be greatly appreiciated.
So, what's an "interesting" resource to you may not be to the next person, and vice versa - in some cases, for example, I may set up NICs independently of my VMs, and want to see them. I don't think there's a way to automatically get just the things you want. What you could do is create a list of resources that are interesting to you (by type), and then use Powershell to create your report:
Get 'em all and filter 'em
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
Get-AzResource | ForEach-Object {
if ($resourceTypes -contains $_.resourceType) {
$resources += [PSCustomObject] #{
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
$resources | Sort-Object ResourceType, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Get 'em type by type (this one loops through subscriptions to which you have access, will print out a line with the current context on each subscription, will restore context to the current subscription when done)
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
$currentContext = Get-AzContext
try {
Get-AzSubscription | ForEach-Object {
$_ | Set-AzContext
$subscriptionName = $_.Name
$resourceTypes | ForEach-Object {
Get-AzResource -ResourceType $_ | ForEach-Object {
$resources += [PSCustomObject] #{
SubscriptionName = $subscriptionName
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
}
} finally {
$currentContext | Set-AzContext
}
$resources | Sort-Object ResourceType, SubscriptionName, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Whichever approach you choose, just customize the $resourceTypes list to contain just the resource types that you want.
To get a list of resource types, I do something like this:
Get-AzResourceProvider -ProviderNamespace Microsoft.Sql |
Select ProviderNamespace -Expand ResourceTypes |
Select #{ L="Provider"; E={ "$($_.ProviderNameSpace)/$($_.ResourceTypeName)" } }
Leave off the -ProviderNamespace Microsoft.Sql if you want to get all resource types, but that will be a long list.

how to operate On List of IIS Application Pools On Remote Server Using Powershell?

I am trying to build powershell program which would:
connect to the remote server
Show number of active IIS app pools on the active server
based on the selection (1,2,3,4,....n etc) it would reset app pool
Can you please give me some tips?
Give this a try:
[Reflection.Assembly]::LoadWithPartialName('Microsoft.Web.Administration')
$sm = [Microsoft.Web.Administration.ServerManager]::OpenRemote('server1')
$sm.ApplicationPools['AppPoolName'].Recycle()
Building upon the answers already given, try the following. It uses powershell remoting, specifically Invoke-Command so you need to familiarise yourself with that.
[cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
param
(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]$ComputerName,
[parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential]$Credential
)
begin
{
if (!($Credential))
{
# Prompt for credentials if not passed in
$Credential = get-credential
}
$scriptBlock = {
Import-Module WebAdministration
# Get all running app pools
$applicationPools = Get-ChildItem IIS:\AppPools | ? {$_.state -eq "Started"}
$i = 0
# Display a basic menu
Write-Host "`nApplication Pools`n"
$applicationPools | % {
"[{0}]`t{1}" -f $i, $($applicationPools[$i].Name)
$i++
}
# Get their choice
$response = Read-Host -Prompt "`nSelect Application Pool to recycle"
# Grab the associated object, which will be null
# if an out of range choice was entered
$appPool = $applicationPools[$response]
if ($appPool)
{
"Recycling '{0}'" -f $appPool.name
$appPool.recycle()
}
}
}
process
{
Invoke-Command -ComputerName $computerName -Credential $credential -ScriptBlock $scriptBlock
}
I cannot help with existing code, but which some links
Check out remote powershell sessions here
Check out the Web Server (IIS) Administration Cmdlets in Windows PowerShell, specialy the Get-WebApplication and Get-WebAppPoolState
If reset means stop, then you could take a look on Stop-WebAppPool

powershell script code to start/stop iis and mssql

I want to start/stop iis and mssql using powershell script code
Means when i run ps script i want to start/stop iis and mssql
I search it on net and i found some code for it but its not working as per my requirement
code:
$iis = get-wmiobject Win32_Service -ComputerName "xyz" -Filter "name='IISADMIN'"
$iis.State=4
if($iis.State -ne "Running")
{
Write-Host "IIS Stop successfuly"
}
above code show me the output IIS Stop successful but iis still running after code execution is this correct code to stop iis using powershell script or something missing please suggest me for iis and mssql also
Thanks in advanced...
You can get all services that depend on IISAdmin service by running:
$query = "ASSOCIATORS OF {Win32_Service.Name='IISAdmin'} WHERE ResultRole=Dependent"
Get-WmiObject -Query $query | Select Name
You can get all services that IISAdmin service depends on by running:
$query = "ASSOCIATORS OF {Win32_Service.Name='IISAdmin'} WHERE ResultRole=Antecedent"
Get-WmiObject -Query $query | Select Name
Now, once you know that the dependent and required services, it is easy to stop.
For example, to stop all services that depend on IISAdmin:
$query = "ASSOCIATORS OF {Win32_Service.Name='IISAdmin'} WHERE ResultRole=Dependent"
Get-WmiObject -Query $query
$services | Foreach-Object { "Stopping $($_.Name)";$_.StopService() }
You need to invoke the StopService method and check the ReturnValue. To get a list of supported methods pipe $iis to Get-Member :
if($iis.State -eq 'Running')
{
$rv = $iis.StopService()
if($rv.ReturnValue -eq 0)
{
Write-Host "IIS Stopped successfuly"
}
else
{
Write-Host "IIS did not stop successfuly. Return value is $($rv.ReturnValue)"
}
}

Azure list running servers

I've been trying to get a list of running VM's but so far I can get the status but I only want the running ones. I need a little help with filting based on powerstate = running
$groups = (Get-AzResourceGroup).ResourceGroupName
foreach($group in $groups)
{
(get-azvm -ResourceGroupName $group -Status | select Name,Powerstate)
}
You are pretty much there, you just need to use where to filter out the PowerState:
$groups = (Get-AzResourceGroup).ResourceGroupName
foreach($group in $groups)
{
(get-azvm -ResourceGroupName $group -Status | select Name,Powerstate | Where { $_.PowerState -eq "VM Running" })
}
Note that the PowerState is VM Running not just Running.

Resources