Powershell

From WikiWiki
Jump to: navigation, search
PowerShell Version Release Date Default Windows Versions Available Windows Versions
PowerShell 1.0 November 2006 Windows Server 2008 (*) Windows XP SP2

Windows XP SP3 Windows Server 2003 SP1

Windows Server 2003 SP2

Windows Server 2003 R2

Windows Vista

Windows Vista SP2


PowerShell 2.0 October 2009 Windows 7

Windows Server 2008 R2 (**)

Windows XP SP3

Windows Server 2003 SP2

Windows Vista SP1

Windows Vista SP2

Windows Server 2008 SP1

Windows Server 2008 SP2

PowerShell 3.0 September 2012 Windows 8

Windows Server 2012

Windows 7 SP1

Windows Server 2008 SP2

Windows Server 2008 R2 SP1

PowerShell 4.0 October 2013 Windows 8.1

Windows Server 2012 R2

Windows 7 SP1

Windows Server 2008 R2 SP1

Windows Server 2012

PowerShell 5.0 April 2014 (***) Windows 10 Windows 8.1

Windows Server 2012 R2


File info (c:\windows\system32\windowspowershell\v1.0\powershell.exe $psversiontable Fileversion OS Version
Compressed : False

Encrypted  : False

Size  :

Hidden  : False

Name  : c:\windows\system32\windowspowershell\v1.0\powershell.exe

Readable  : True

System  : False

Version  : 6.1.7600.16385

Writeable  : True

CLRVersion: 2.0.50727.5485

BuildVersion: 6.1.7601.17514

PSVersion : 2.0

WSManStackVersion : 2.0

PSCompatibleVersions : {1.0, 2.0}

SerializationVersion: 1.1.0.1

PSRemotingProtocolVersion : 2.1

6.1.7600.16385 2008 R2
Compressed : False

Encrypted  : False

Size  :

Hidden  : False

Name  : c:\windows\system32\windowspowershell\v1.0\powershell.exe

Readable  : True

System  : False

Version  : 6.3.9600.17415

Writeable  : True

PSVersion  : 4.0

WSManStackVersion  : 3.0

SerializationVersion : 1.1.0.1

CLRVersion  : 4.0.30319.34209

BuildVersion  : 6.3.9600.17400

PSCompatibleVersions  : {1.0, 2.0, 3.0, 4.0}

PSRemotingProtocolVersion : 2.2

6.3.9600.17415 8.1
Compressed : False

Encrypted  : False

Size  :

Hidden  : False

Name  : c:\windows\system32\windowspowershell\v1.0\powershell.exe

Readable  : True

System  : False

Version  : 6.2.9200.16384

Writeable  : True

PSVersion  : 3.0

WSManStackVersion  : 3.0

SerializationVersion  : 1.1.0.1

CLRVersion  : 4.0.30319.18449

BuildVersion  : 6.2.9200.17065

PSCompatibleVersions  : {1.0, 2.0, 3.0}

PSRemotingProtocolVersion : 2.2

6.2.9200.16384 2012
Compressed : False

Encrypted  : False

Size  :

Hidden  : False

Name  : c:\windows\system32\windowspowershell\v1.0\powershell.exe

Readable  : True

System  : False

Version  : 6.3.9600.16384

Writeable  : True

PSVersion  : 4.0

WSManStackVersion  : 3.0

SerializationVersion  : 1.1.0.1

CLRVersion  : 4.0.30319.33440

BuildVersion  : 6.3.9600.16384

PSCompatibleVersions  : {1.0, 2.0, 3.0, 4.0}

PSRemotingProtocolVersion  : 2.2

6.3.9600.16384 2012 R2


  • get-help
  • get-command
  • get-module
  • $PSVersionTable.psversion
  • get-history
  • get-process | get-member
  • Get-Host
  • $obj | select -first 5
  • $psversiontable
  • Get-ChildItem Env:
  • get-adgroup "domain admins" -Server domain.lcl -Properties * | select -Expand members


Known Tricks

foreach($var in $array) == | %{$_}

-like "*string*"

$var | ft * -auto | out-default

Easy powershell in cmd command

Powershell.exe -command - < configure-iis.ps1

invoke bluescreen bsod

function Invoke-BlueScreen
{
    Add-Type "
      using System;
      using System.Runtime.InteropServices;
      public class PInvoke
      {
          [DllImport(`"user32.dll`")]
          public static extern IntPtr CreateDesktop(string desktopName, IntPtr device, IntPtr deviceMode, int flags, long accessMask, IntPtr attributes);
      }
    "

    [PInvoke]::CreateDesktop("BSOD", [IntPtr]::Zero, [IntPtr]::Zero, 0, $null, [IntPtr]::Zero)
}

self elevate

Start-Process PowerShell –Verb RunAs

or

# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
 
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
 
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
   {
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "DarkBlue"
   clear-host
   }
else
   {
   # We are not running "as Administrator" - so relaunch as administrator
   
   # Create a new process object that starts PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
   
   # Specify the current script path and name as a parameter
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
   
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
   
   # Exit from the current, unelevated, process
   exit
   }
 
# Run your code that needs to be elevated here
Write-Host -NoNewLine "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")


check authenticity of process

PS C:\WINDOWS\system32> (get-process svchost | select-object path).path | Get-AuthenticodeSignature


    Directory: C:\WINDOWS\system32


SignerCertificate                         Status                                 Path
-----------------                         ------                                 ----
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe
9C4F3BDB96A8F46DB59EDBB7A65CC090841236AA  Valid                                  svchost.exe


#get info about domain
get-addomain

Sign a Powershell script

$cert = Get-ChildItem cert:\CurrentUser\My -CodeSigningCert
Set-AuthenticodeSignature -Certificate $cert -FilePath C:\users\deswale\Desktop\lockoutstatus.ps1
Get-AuthenticodeSignature .\lockoutstatus.ps1 | fl *

Reboot Reason

function shutdownreason()
{

Param
(
[Parameter(Mandatory=$true)][string] $ServerName
)
	if(test-connection $ServerName -Count 1 -Quiet)
	{
		$ShutdownStats = @() 
		$list = Get-WinEvent -ComputerName $ServerName -FilterHashtable @{LogName='System';Id=1074} -ErrorAction Stop -Credential $cred | Sort-Object -Property TimeCreated -Descending 

		foreach($item in $list)
		{
			$ShutdownStats += New-Object -TypeName PSObject -Property @{ 
				Name = $item.properties[1].value
				Reason = $item.properties[2].value
				Account = $item.properties[6].value
				Time = $item.timecreated
			}
		}
		$ShutdownStats | Format-Table 
	}
	else
	{
		write-host "server $servername bestaat niet"
	}
}

Shutdown Computer

Stop-Computer –computer $_ –Credential $creds -force

Get Lockout Location

as seen on http://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab

Function Get-LockedOutLocation 
{ 
<# 
.SYNOPSIS 
    This function will locate the computer that processed a failed user logon attempt which caused the user account to become locked out. 
 
.DESCRIPTION 
    This function will locate the computer that processed a failed user logon attempt which caused the user account to become locked out.  
    The locked out location is found by querying the PDC Emulator for locked out events (4740).   
    The function will display the BadPasswordTime attribute on all of the domain controllers to add in further troubleshooting. 
 
.EXAMPLE 
    PS C:\>Get-LockedOutLocation -Identity Joe.Davis 
 
 
    This example will find the locked out location for Joe Davis. 
.NOTE 
    This function is only compatible with an environment where the domain controller with the PDCe role to be running Windows Server 2008 SP2 and up.   
    The script is also dependent the ActiveDirectory PowerShell module, which requires the AD Web services to be running on at least one domain controller. 
    Author:Jason Walker 
    Last Modified: 3/20/2013 
#> 
    [CmdletBinding()] 
 
    Param( 
      [Parameter(Mandatory=$True)] 
      [String]$Identity       
    ) 
 
    Begin 
    {  
        $DCCounter = 0  
        $LockedOutStats = @()    
                 
        Try 
        { 
            Import-Module ActiveDirectory -ErrorAction Stop 
        } 
        Catch 
        { 
           Write-Warning $_ 
           Break 
        } 
    }#end begin 
    Process 
    { 
         
        #Get all domain controllers in domain 
        $DomainControllers = Get-ADDomainController -Filter * 
        $PDCEmulator = ($DomainControllers | Where-Object {$_.OperationMasterRoles -contains "PDCEmulator"}) 
         
        Write-Verbose "Finding the domain controllers in the domain" 
        Foreach($DC in $DomainControllers) 
        { 
            $DCCounter++ 
            Write-Progress -Activity "Contacting DCs for lockout info" -Status "Querying $($DC.Hostname)" -PercentComplete (($DCCounter/$DomainControllers.Count) * 100) 
            Try 
            { 
                $UserInfo = Get-ADUser -Identity $Identity  -Server $DC.Hostname -Properties AccountLockoutTime,LastBadPasswordAttempt,BadPwdCount,LockedOut -ErrorAction Stop 
            } 
            Catch 
            { 
                Write-Warning $_ 
                Continue 
            } 
            If($UserInfo.LastBadPasswordAttempt) 
            {     
                $LockedOutStats += New-Object -TypeName PSObject -Property @{ 
                        Name                   = $UserInfo.SamAccountName 
                        SID                    = $UserInfo.SID.Value 
                        LockedOut              = $UserInfo.LockedOut 
                        BadPwdCount            = $UserInfo.BadPwdCount 
                        BadPasswordTime        = $UserInfo.BadPasswordTime             
                        DomainController       = $DC.Hostname 
                        AccountLockoutTime     = $UserInfo.AccountLockoutTime 
                        LastBadPasswordAttempt = ($UserInfo.LastBadPasswordAttempt).ToLocalTime() 
                    }           
            }#end if 
        }#end foreach DCs 
        $LockedOutStats | Format-Table -Property Name,LockedOut,DomainController,BadPwdCount,AccountLockoutTime,LastBadPasswordAttempt -AutoSize 
 
        #Get User Info 
        Try 
        {   
           Write-Verbose "Querying event log on $($PDCEmulator.HostName)" 
           $LockedOutEvents = Get-WinEvent -ComputerName $PDCEmulator.HostName -FilterHashtable @{LogName='Security';Id=4740} -ErrorAction Stop | Sort-Object -Property TimeCreated -Descending 
        } 
        Catch  
        {           
           Write-Warning $_ 
           Continue 
        }#end catch      
                                  
        Foreach($Event in $LockedOutEvents) 
        {    

           If($Event | Where {$_.Properties[2].value -match $UserInfo.SID.Value}) 
           {  
               
              $var=$Event | Select-Object -Property @( 
                @{Label = 'User';               Expression = {$_.Properties[0].Value}} 
                @{Label = 'DomainController';   Expression = {$_.MachineName}} 
                @{Label = 'EventId';            Expression = {$_.Id}} 
                @{Label = 'LockedOutTimeStamp'; Expression = {$_.TimeCreated}} 
                @{Label = 'Message';            Expression = {$_.Message -split "`r" | Select -First 1}} 
                @{Label = 'LockedOutLocation';  Expression = {$_.Properties[1].Value}} 
              ) 

			$var | ft *
            }#end ifevent 
             
       }#end foreach lockedout event 
        
    }#end process 
    
}#end function

Get file version

$list="server1","server2"
$list= get-ADComputer -Filter {OperatingSystem -Like "Windows Server*2003*"}
$hashlist=@{}
$admin=get-credential
foreach($computer in $list){

$answer = Get-WMIObject -Computer $computer.DNSHostName -credential $admin -Query "SELECT * FROM CIM_DataFile WHERE Drive ='C:' AND Path='\\windows\\system32\\' AND FileName='crypt32' AND Extension='dll'" | select Version
$hashlist[$computer]=$answer
}
$hashlist | export-csv export.csv

Convert to csv

$collection = @()
foreach ($key in $hashlist.Keys) {
   $store = "" | select "OS","count"
   $store.OS = "$Key"
   $store.count = $hashlist.$Key
   $collection += $store
}
$collection | Export-Csv "OSCount2.csv" -NoTypeInformation

of voor nen hashtable

$OutputTable = $allrenamedfolders.getEnumerator() | foreach{
	New-Object PSObject -Property ([ordered]@{Name = $_.Name;Value = $_.Value})
}
$OutputTable | Export-CSV allRenamedFolders.csv -NoTypeInformation


search all attributes for something like "pass"

$allobj=Get-ADUser -filter * | Get-ADObject -Properties *
$allobj | %{$_.getenumerator()} |  %{ $_.value }  | where{$_ -like "*pass*"}


get-recursive

recursive search domain groups on domain controller

$Recurse = $true
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$group=[System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($ct,'domain admins')
$group.GetMembers($Recurse) | ft


uac-translate

convert an unreadable uac ldap value to something more usefull - for example uac-translate 514 will return ACCOUNTDISABLE and NORMAL_ACCOUNT

function uac-translate([int]$value)
{
$flags = @("","ACCOUNTDISABLE","", "HOMEDIR_REQUIRED","LOCKOUT", "PASSWD_NOTREQD","PASSWD_CANT_CHANGE", "ENCRYPTED_TEXT_PWD_ALLOWED","TEMP_DUPLICATE_ACCOUNT", "NORMAL_ACCOUNT", "","INTERDOMAIN_TRUST_ACCOUNT", "WORKSTATION_TRUST_ACCOUNT","SERVER_TRUST_ACCOUNT", "", "", "DONT_EXPIRE_PASSWORD", "MNS_LOGON_ACCOUNT", "SMARTCARD_REQUIRED","TRUSTED_FOR_DELEGATION", "NOT_DELEGATED","USE_DES_KEY_ONLY", "DONT_REQ_PREAUTH","PASSWORD_EXPIRED", "TRUSTED_TO_AUTH_FOR_DELEGATION")
1..($flags.length) | ? {$value -band [math]::Pow(2,$_)} | % { $flags[$_] }
}

profile

if(!(Test-path $profile))
{New-item –type file –force $profile}
Notepad $profile


get-password

random generate password

#alphanumeric
-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 15 | % {[char]$_})
#ascii
-join ((33..125) | Get-Random -Count 15 | % {[char]$_})