Powershell

From WikiWiki
Jump to navigation Jump to search
  • get-help
  • get-command
  • get-module
  • $PSVersionTable.psversion
  • get-history
  • get-process | get-member
  • Get-Host
  • $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

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