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

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

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"

Disable all site creation except for a certain group

I want to lock down site creation to a certain group of admin suresh. We have created a group for this, but what do I tell the SharePoint Admin to do in order to achieve this?
To lock down site creation, you basically need to run a few PowerShell commands as below using Azure AD PowerShell. Run them commands with Global admin priviledges.
I am assuming that you have created an Azure AD group with certain users who will have access to create the site.
$creds = Get-Credential
Connect-AzureAD -Credential $creds
$group = Get-AzureADGroup -All $True | Where-Object {$_.DisplayName -eq "ENTER GROUP DISPLAY NAME HERE"}
$policySetting = Get-AzureADDirectorySetting | where-object {$_.displayname -eq "Group.Unified"}
if($policySetting -eq $null) {
$template = Get-AzureADDirectorySettingTemplate | Where-Object {$_.DisplayName -eq "Group.Unified"}
$settings = $template.CreateDirectorySetting()
$settings["EnableGroupCreation"] = $false
$settings["GroupCreationAllowedGroupId"] = $group.ObjectId
$policySetting = New-AzureADDirectorySetting -DirectorySetting $settings
}
else{
$policySetting["EnableGroupCreation"] = $false
$policySetting["GroupCreationAllowedGroupId"] = $group.ObjectId
Set-AzureADDirectorySetting -Id $policySetting.Id -DirectorySetting $policySetting
}
Links:
Installing the Azure AD module
Code modified from - Managing Office 365 group creation using Azure AD PowerShell v2

Composing a script in Powershell V3

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;
}

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)"
}
}

Validating PowerShell PSCredential

Let's say I have a PSCrendential object in PowerShell that I created using Get-Credential.
How can I validate the input against Active Directory ?
By now I found this way, but I feel it's a bit ugly :
[void][System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")
function Validate-Credentials([System.Management.Automation.PSCredential]$credentials)
{
$pctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain, "domain")
$nc = $credentials.GetNetworkCredential()
return $pctx.ValidateCredentials($nc.UserName, $nc.Password)
}
$credentials = Get-Credential
Validate-Credentials $credentials
[Edit, two years later] For future readers, please note that Test-Credential or Test-PSCredential are better names, because Validate is not a valid powershell verb (see Get-Verb)
I believe using System.DirectoryServices.AccountManagement is the less ugly way:
This is using ADSI (more ugly?):
$cred = Get-Credential #Read credentials
$username = $cred.username
$password = $cred.GetNetworkCredential().password
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)
if ($domain.name -eq $null)
{
write-host "Authentication failed - please verify your username and password."
exit #terminate the script.
}
else
{
write-host "Successfully authenticated with domain $domain.name"
}
I was having a similar issue with an installer and required to verify the service account details supplied. I wanted to avoid using the AD module in Powershell as I wasn't 100% this would be installed on the machine running the script.
I did the test using the below, it is slightly dirty but it does work.
try{
start-process -Credential $c -FilePath ping -WindowStyle Hidden
} catch {
write-error $_.Exception.Message
break
}

Resources