Posts

Showing posts with the label PowerShell

View PowerShell commands executed history

Look at below files at the below location to view the PowerShell commands executed history: ConsoleHost_history.txt Visual Studio Code Host_history.txt C:\Users\<UserName>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine

Using Proxy to Install-Module

Find-Module -Name PowerShellGet   # To look for a module Find-Module -Name PowerShellGet | Install-Module  # To look for a module and install that Using Proxy to connect to Internet: Import the proxy settings from Internet Explorer parameters: netsh winhttp import proxy source=ie or set them manually: netsh winhttp set proxy "192.168.0.14:80" To view current proxy setting: netsh winhttp show proxy To reset the winhttp proxy : netsh winhttp reset proxy If you are signed in using your domain account and your proxy supports NTLM/AD authentication, you can use the credentials of the current user to authenticate on the proxy server (you won’t have to enter your username/password): $Wcl = new-object System.Net.WebClient $Wcl.Headers.Add(“user-agent”, “PowerShell Script”) $Wcl.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials If you have to authenticate on the proxy server manually, run the following commands and specify use...

Get Powershell Foreground colors

Below Powershell command lists all foreground colors available: [Enum]::GetValues([System.ConsoleColor]) Example: PS C:\> [Enum]::GetValues([System.ConsoleColor])Black DarkBlue DarkGreen DarkCyan DarkRed DarkMagenta DarkYellow Gray DarkGray Blue Green Cyan Red Magenta Yello Ref :  https://stackoverflow.com/questions/20541456/list-of-all-colors-available-for-powershell Get the colours displayed in screen with below script: $colors = [ enum ]:: GetValues ([ System . ConsoleColor ]) Foreach ( $bgcolor in $colors ){ Foreach ( $fgcolor in $colors ) { Write - Host "$fgcolor|" - ForegroundColor $fgcolor - BackgroundColor $bgcolor - NoNewLine } Write - Host " on $bgcolor" }

PowerShell Script to get all registry keys and values

Below one liner may help to get all registry keys and their values under given path: Get-Item ' ' | %{Get-ItemProperty -Path $_.PSPath} Example registry path :  HKLM:\SOFTWARE\7-Zip Get-Item ' HKLM:\SOFTWARE\7-Zip'   | %{Get-ItemProperty -Path $_.PSPath} Output: PS C:\> Get-Item 'HKLM:\SOFTWARE\7-Zip' | %{Get-ItemProperty -Path $_.PSPath} Path         : C:\Program Files\7-Zip\ Path64       : C:\Program Files\7-Zip\ PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\7-Zip PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE PSChildName  : 7-Zip PSProvider   : Microsoft.PowerShell.Core\Registry

Get PowerShell version in a Windows system

Ways to get PowerShell version in a Windows system $PSVersionTable.PSVersion (Available in PS version 2 or higher) get-host (For PS version 1) powershell -Command "$PSVersionTable.PSVersion" powershell -command "(Get-Variable PSVersionTable -ValueOnly).PSVersion " Outputs: $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 3 0 -1 -1 get-host Name : ConsoleHost Version : 3.0 InstanceId : 9b7e8224-e1d5-4b22-b0cb-53f19cd9c5b8 UI : System.Management.Automation.Internal.Host.InternalHostUserInterface CurrentCulture : en-US CurrentUICulture : en-US PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy IsRunspacePushed : False Runspace : System.Management.Automation.Runspaces.LocalRunspace

PowerShell command to get last modified files

PowerShell command to get last modified files: Dir " " -r | ? {! $_.PSIsContainer} | sort LastWriteTime | select LastWriteTime, FullName -last 20 | sort LastWriteTime –Descending | ft -autosize Example: Dir " c:\temp " -r | ? {! $_.PSIsContainer} | sort LastWriteTime | select LastWriteTime, FullName -last 20 | sort LastWriteTime –Descending | ft -autosize

Simple array in PowerShell script

Here is a baseline of nested arrays in PowerShell script: PS: Currently output is not sorted, looking for improvements: <#  JD Script to find Last logon time #> $array = @() foreach ($ID in $IDs) { $User = Get-ADUser -Server $dc -Filter {Name -like $ID} -Properties * $obj = New-Object psobject -Property @{  Name = $User.Name            LastLogonDate = $User.LastLogonDate             } $array += $obj }                       #$array | Select * | FT -AutoSize $array | Export-Csv -path $outfile -NoTypeInformation  

PowerShell Script to Get Last logged-on time of AD users of different domain

Scenario: You need to get Last logged-on time of AD users of different domain. Below are the steps: Step 1 : Find a DC of that domain: Get-ADDomainController -DomainName -Discover -NextClosestSite Above command outputs server name of given domain. Step 2: Get-ADUser properties in that server Get-ADUser -Server -Filter {Name -like " "} | Get-ADObject -Properties lastLogon Possible Filters that can be used: GivenName                : First Name Surname                      : Last name Name                          :Login id SamAccountName      :  Login id UserPrincipalName     : Login id@domain.com My PowerShell script: $GivenDomain = "mydomain.com" $IDs = @ ( "myadaccount1" " myadaccount2 " " myadaccount3 " " myadaccount4 " ) $ErrorActionPreferenc...

Ways to execute PowerShell (PS1) scripts in remote computers

Below are ways to execute PowerShell (PS1) scripts in remote computers: Example 1: invoke-command -computerName MySrv1 -filepath .\test.ps1 Example 2: Get the version of the PowerShell host running on a remote computer: invoke-command -computername server64 -scriptblock {(get-host).version} Example 3: Get the version of the PowerShell host running on a list of remote computers (computers.txt): PS C:\> $version = invoke-command -computername (get-content computers.txt) -scriptblock {(get-host).version} PS C:\> $version Example 4: Run the Sample.ps1 script on all of the computers listed in the Servers.txt file. Using the -FilePath parameter to specify the script file has the effect that the content of the script is automatically copied into a script block and then passed to and run on each of the remote computers: PS C:\> invoke-command -comp (get-content servers.txt) -filepath c:\scripts\sample.ps1 -argumentlist Process, Service Alternatives method: Inv...

Command to find specific patch is installed or not

I wanted to check if  KB KB2998527 is installed in few of my servers. Powershell on local computer: get-hotfix -id KB2998527 PowerShell command to look in remote server: get-hotfix -id KB2998527 -ComputerName myservername If you have a list of computer names, you can pass it to a command to check multiple machines. For example: get-content computers.txt | foreach \{ if (!(get-hotfix -id KB974332 -computername $_)) \{ add-content $_ -path Missing-KB974332.txt \}\} WMI: wmic qfe get hotfixid | find "KB2998527" wmic qfe | find "KB2998527" To get detailed report: wmic qfe list full /format:htable >C:\Temp\hotfixes.htm

PowerShell commands

PS get-command -Module FailoverClusters - To get all commands with clusters. Create user account in AD: New-ADUser –Name adfsService Set-ADAccountPassword adfsService Enable-ADAccount adfsService Regional settings: Set-Culture -CultureInfo < de-DE> - To set regional setting to German get-adgroupmember $MyGroup | select name - This will list down just names of members of the group Get-ADPrincipalGroupMembership | select name - This will list groups the user is member of. Get installed server roles: Get-WindowsFeature | where {$_.installed -eq $true} | select displayname, name, installed Change network profile to Private: Set-NetConnectionProfile -InterfaceAlias "nic1-storage" -NetworkCategory Private Set-NetConnectionProfile -InterfaceAlias "nic2-admin" -NetworkCategory Private