Tuesday, August 10, 2021

Powershell Useful Commands

Import Web Admin Module

Import-Module WebAdministration

Default IIS Log Directory

(Get-WebConfigurationProperty '/system.applicationHost/sites/siteDefaults' -Name 'logfile.directory').Value

Get All Websites on The IIS

PS>Get-WebSite

Name             ID   State      Physical Path                  Bindings

----             --   -----      -------------                  --------

mypool              2    Stopped    E:\mypool                         http *:80:

                                                                https *:443: sslFlags=0

mypoolpoc           3    Started    e:\mypoolPoc                      http *:80:

OR

# To show configured IIS sites:

# -----------------------------------------------------------------------------

Get-ChildItem IIS:\Sites

Stop Website

PS> Stop-WebSite -Name "mysite"


Start Website

PS> Start-WebSite -Name 'mysite'


Invoke URL

PS>Invoke-WebRequest -URI http://localhost


Telnet

PS> Test-NetConnection <SERVERNAME> -Port <PORT>


Tail File

PS> Get-Content  .\error.log -Tail 2 –Wait


Last 10 reboot

PS> Get-WinEvent -FilterHashtable @{logname = 'System'; id = 1074, 6005, 6006, 6008} -MaxEvents 8 | Format-Table -wrap


Install IIS Server

Install-WindowsFeature -name Web-Server -IncludeManagementTools


IIS Server Version

Get-ItemProperty -Path registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\ | Select-Object

[System.Diagnostics.FileVersionInfo]::GetVersionInfo(“C:\Windows\system32\notepad.exe”).FileVersion

reg query HKLM\SOFTWARE\Microsoft\InetStp\


Windows Server

(Get-WmiObject -class Win32_OperatingSystem).Caption

systeminfo | findstr /B /C:"OS Name" /C:"OS Version"


Share Folder with Multiple Users

net share GlobalScape=E:\Globalscape /grant:"DOMAIN\ADGROUP",FULL  /grant:"DOMAIN\USERNAME",FULL


Get Permission on the Folder

Get-SmbShareAccess -Name "Globalscape"

(Get-Acl -Path \\HOSTNAME\GLOBALSCAPE).Access | Format-Table -AutoSize


Change Permission on the Folder

(Get-ACL -Path .\Certificates\).Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize

$ACL = Get-ACL -Path ".\Certificates"

$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("username","FullControl","Allow")

$ACL.SetAccessRule($AccessRule)

$ACL | Set-Acl -Path ".\Certificates"

(Get-ACL -Path ".\Certificates").Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize


Remove Permission on the Folder

$ACL = Get-Acl -Path ".\sample.txt"

$ACL.SetAccessRuleProtection($true,$false)

$ACL | Set-Acl -Path ".\sample.txt"

(Get-ACL -Path ".\sample.txt").Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize

$ACL = Get-ACL -Path ".\sample.txt"

$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","Allow")

$ACL.RemoveAccessRule($AccessRule)

$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\SYSTEM","FullControl","Allow")

$ACL.RemoveAccessRule($AccessRule)

$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users","ReadAndExecute, Synchronize","Allow")

$ACL.RemoveAccessRule($AccessRule)

$ACL | Set-Acl -Path ".\sample.txt"

(Get-ACL -Path ".\sample.txt").Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize

$ACL = Get-ACL -Path ".\sample.txt"

$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\SYSTEM","FullControl","Allow")

$ACL.RemoveAccessRule($AccessRule)

$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Users","ReadAndExecute, Synchronize","Allow")

$ACL.RemoveAccessRule($AccessRule)

$ACL | Set-Acl -Path ".\sample.txt"

(Get-ACL -Path ".\sample.txt").Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize


Unzip the .zip file:

PS E:\Program Files\Java> Expand-Archive -Force jdk1.8.0_271.zip .\jre-8u271-windows-x64.tar\


Get Powershell Version

Get-Host | Select-Object Version


RAM Size

([Math]::Round(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory/1GB),0))


CPU

Get-WmiObject -Class Win32_Processor | Select-Object -Property Name, Number*


Show Certificates

Get-ChildItem -Path Cert:\LocalMachine\Root


Import Certificates

Import-Certificate -FilePath "E:\Maintenance\wsctt.pem" -CertStoreLocation Cert:\LocalMachine\Root


Delete Service

(Get-Service).where({$_.Name -like 'wpnuserservice*'}) | Select-Object -Property *

$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"

$service.delete()


Get  IIS Application Pool Identity Account Passwords in Clear Text

Method#1:

Get-CimInstance -Namespace root/MicrosoftIISv2 -ClassName IIsApplicationPoolSetting -Property Name, WAMUserName, WAMUserPass | select Name, WAMUserName, WAMUserPass

If errors out then run

Add-WindowsFeature Web-WMI | Format-List


Method#2:

$appPools = Get-WebConfiguration -Filter '/system.applicationHost/applicationPools/add'

foreach($appPool in $appPools)

{

if($appPool.ProcessModel.identityType -eq "SpecificUser")

{

Write-Host $appPool.Name -ForegroundColor Green -NoNewline

Write-Host " -"$appPool.ProcessModel.UserName"="$appPool.ProcessModel.Password

}

}


Install Module Offline

On Local Machine:

Save-Module IISAdministration -Path \\HOSTNAME\E$\Maintenance -Repository PSGallery

On Server:

cd "C:\Program Files\WindowsPowerShell\Modules"

Copy-Item E:\Maintenance\IISAdministration -Destination .\ -Recurse

Import-Module IISAdministration

Get-Module IISAdministration


Test HTTPS URL

Enable TLS1.2

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12


Ignore Certificate

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)

{

$certCallback = @"

    using System;

    using System.Net;

    using System.Net.Security;

    using System.Security.Cryptography.X509Certificates;

    public class ServerCertificateValidationCallback

    {

        public static void Ignore()

        {

            if(ServicePointManager.ServerCertificateValidationCallback ==null)

            {

                ServicePointManager.ServerCertificateValidationCallback +=

                    delegate

                    (

                        Object obj,

                        X509Certificate certificate,

                        X509Chain chain,

                        SslPolicyErrors errors

                    )

                    {

                        return true;

                    };

            }

        }

    }

"@

    Add-Type $certCallback

 }

[ServerCertificateValidationCallback]::Ignore()


Execute the command

Invoke-WebRequest -URI https://localhost:8443 -UseBasicParsing


Get AppPool Recycling Settings

$ConfigSection = Get-IISConfigSection -SectionPath "system.applicationHost/applicationPools"

$SitesCollection = Get-IISConfigCollection -ConfigElement $ConfigSection

$Site = Get-IISConfigCollectionElement -ConfigCollection $SitesCollection -ConfigAttribute @{"name" = "myapppool"}

$recycling = Get-IISConfigElement -ConfigElement $Site -ChildElementName "recycling"

$flags = $recycling.Attributes["logEventOnRecycle"].Value


$onRecycle = @{

'Time' = [bool]($flags -band 1) # Specific Time

'Requests' = [bool]($flags -band 2) # Request Limit Exceeded

'Schedule' = [bool]($flags -band 4) # Regular Time Interval

'Memory' = [bool]($flags -band 8) # Virtual Memory Limit Exceeded

'IsapiUnhealthy' = [bool]($flags -band 16) # Isapi Reported Unhealthy

'OnDemand' = [bool]($flags -band 32) # Manual Recycle

'ConfigChange' = [bool]($flags -band 64) # Application Pool Configuration Changed

'PrivateMemory' = [bool]($flags -band 128) # Private Memory Limit Exceeded

}

$onRecycle


Find files modified in last 21 days

$days_to_check=$(Get-Date).AddDays(-21)

Get-ChildItem E:\Inetpub\*.* -Recurse | where { $_.LastWriteTime -gt $days_to_check } | Foreach {

"File Name: " + $_.Name


Web Module Installed on IIS

PS> Get-WebGlobalModule


Get Scheduled Task Details

PS> Get-ScheduledTask -TaskName VU* | Format-Table State, TaskName, Triggers

State TaskName Triggers
----- -------- --------
Ready VU_AUTO_FileXfer_Daily {MSFT_TaskDailyTrigger}

PS> Get-ScheduledTask -TaskName VU* | Get-ScheduledTaskInfo | Format-Table TaskName, LastRuntime, NextRuntime

TaskName LastRuntime NextRuntime
-------- ----------- -----------
VU_AUTO_FileXfer_Daily 8/10/2021 12:00:00 PM 8/11/2021 12:00:00 PM