Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

22 February 2023

Powershell generic List

list are allways to be used what the collection has to grow or shrink.

arrays should be used only when the collection have a fixed length and it will not change.


[System.Collections.Generic.List[string]]::new()

[System.Collections.Generic.List[int]]::new()

[System.Collections.Generic.List[Object]]::new()


Powershell - ignoring output performance

 

(Measure-Command -Expression { [void]$(1..100000) }).Milliseconds

53

(Measure-Command -Expression { $null = $(1..100000) }).Milliseconds

49

(Measure-Command -Expression { $(1..100000) > $null }).Milliseconds

62

(Measure-Command -Expression { $(1..100000) | Out-Null }).Milliseconds

393

17 December 2021

Return line from CSV file (data)

 in order to find and return a specific line from a csv file (data)


$Recepies = Iomport-CSV C:\temp\recepies.scv

$Recepies.Where({$PSItem.Ingredient_1 -eq 'potato'})

24 February 2021

Search and install packages from powershellgallery

use this command to modify TLS settings if you get an error running the below commands
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

search for all available package providers
Find-PackageProvider

search for a specific package provider
Find-PackageProvider -name nuget

install a package provider
Install-PackageProvider -Name nuget


after you have a package provider setup you can search for packages

search for a specific package. it supports wildcard in name
Find-Package -Name *AzureAD*

install package
Install-Package -Name AzureAD


Change domain for microsoft 365 / azure users from powershell

modify TLS settings if you get errors running commands below
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12


Install-Module -Name MSOnline
(from https://www.powershellgallery.com )

 

Connect-MsolService

$AllMsolUsers = Get-MsolUser -All
$AllToModify = $AllMsolUsers | Where-Object -FilterScript { ($PSItem.Licenses.AccountSkuId -eq 'o365:STANDARDPACK') -and ($PSItem.UserType -eq 'Member') -and $PSItem.IsLicensed}

foreach($User in $AllToModify){

    if($User.UserPrincipalName.Contains('@o365.onmicrosoft.com')){

        $NewPrincipal = $User.UserPrincipalName.Replace('@o365.onmicrosoft.com','@domain.com')

        Set-MsolUserPrincipalName -NewUserPrincipalName $NewPrincipal -UserPrincipalName $User.UserPrincipalName

    }

}


23 February 2021

21 February 2021

Create hashtable from PSObject

$GroupDataObjectHash = [ordered]@{}

$GroupDataObject.PSObject.Properties.Name | %{$GroupDataObjectHash.Add($PSItem, $GroupDataObject.$PSItem)}

25 May 2018

Find filesystem blocksize on windows with powershell

Get-WmiObject -Class Win32_Volume | Select-Object Name, Label, BlockSize

Get-CimInstance -ClassName Win32_Volume | Select-Object Name, Label, BlockSize

22 May 2018

Find exception full name

$Error[0] | Select-Object *

Exception  : Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException: The specified account already exists



$Error[0].Exception.GetType().FullName
Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException

02 March 2018

Get-WmiObject hangs

for some reason Get-WmiObject hangs on some of the computers that is queryes and the powershell console must be restarted.

in order to overcome this problem a used "-AsJob" parameter


$Job = Get-WmiObject -Class win32_computersystem -AsJob -ComputerName ServerName | Wait-Job -Timeout 30
$Result = $Job | Receive-Job

27 January 2018

Find FSMO roles from powershell

Get-ADDomainController -Filter * | Select-Object Name, Site,  OperatingSystem, OperationMasterRoles

21 January 2018

Search eventlogs with xml filter

# 4625 bad password in client log
# 4771 bad password in DC log
# 4740 lockout in DC log
# <Select Path="Security">*[System[(EventID=4740 or EventID=4771)]]</Select>

[xml]$XMLFilter = @"
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">*[System[(EventID=4740)]]</Select>
  </Query>
</QueryList>
"@

$AllDomainControllers = Get-ADDomainController -Filter *

$AllEvents = @()

foreach($DC in $AllDomainControllers){
    $Events = @()
    $Events += Get-WinEvent -FilterXml $XMLFilter -ComputerName $DC.HostName -ErrorAction SilentlyContinue
    $AllEvents += $Events
    $DC.HostName + ' ' + $Events.Length
}

foreach($Event in $AllEvents){
    $EventXMLData = [xml]$Event.ToXml()
    for($i=0; $i -lt $EventXMLData.Event.EventData.Data.Count; $i++){
        $Name = $EventXMLData.Event.EventData.Data[$i].Name
        $Value = $EventXMLData.Event.EventData.Data[$i].'#text'
        Add-Member -InputObject $Event -MemberType NoteProperty -Force -Name $Name -Value $Value
    }
}

$AllEvents |
Select-Object TargetUsername, MachineName, TimeCreated,IpAddress, ID |
Format-Table


Active directory domain user last logon date and time


"lastLogon" attribute is per domain controller - is not replicated to other domain controllers in the domain and each domain cotroller has his own information.

"lastLogonTimeStamp" is replicated in the domain (all domain controllers have the same updated information).

the date is stored in 100 miliseconds interval since 01.01.1601 (Juanuary 1, 1601)

to convert from System.Int64 we can use "FromFileTime" static method of DateTime class:

[System.DateTime]::FromFileTime($ADUser.lastlogon)
[System.DateTime]::FromFileTime($ADUser.lastlogontimestamp)

http://msdn.microsoft.com/en-us/library/ms676824(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms676823(VS.85).aspx



List active directory group membership changes


$ADGroup = Get-ADGroup -Identity 'Domain Admins'
Get-ADReplicationAttributeMetadata -Object $ADGroup.DistinguishedName -Server dc1 -ShowAllLinkedValues

in the output the "AttributeName" is the attribute that was changed - we should search for the "member" attribute.

"AttributeValue" is the value assigned to the attribute.
"FirstOriginatingCreateTime" is the time the value was added.
"LastOriginatingDeleteTime" is the time the value was deleted - but only if is different from "1/1/1601 2:00:00 AM"

13 November 2017

Ldap filter to recursively find all groups a user is member


Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=CN=Uservane,OU=Users,DC=domain,DC=local)"

15 February 2017

Search for expiring domain accounts


Search-ADAccount -AccountExpiring -TimeSpan "365" 

16 January 2017

Keyboard shortcuts for Powershell console

Ctrl + End - delete all text after the cursor
Ctrl + Home - delete all text before the cursor

15 December 2016

Calculate MD5 with powershell


[Reflection.Assembly]::LoadWithPartialName("System.Web")
[System.Web.Security.FormsAuthentication]::HashPasswordForStoringInConfigFile("p@ssw0rd", "MD5")

08 December 2016

Display a MessageBox from PowerShell


[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Windows.Forms.MessageBox]::Show("Hello there !")
[System.Windows.Forms.MessageBox]::Show("Hello there !", "Some title")


you can also have buttons like:

0: OK
1: OK Cancel
2: Abort Retry Ignore
3: Yes No Cancel
4: Yes No
5: Retry Cancel

[System.Windows.Forms.MessageBox]::Show("Hello there !", "Some title", 4)



you can olso read the unswer from the user:

$Unswer = [System.Windows.Forms.MessageBox]::Show("Hello there !", "Some title", 4)
if ($Unswer -eq "YES" ) { # perform sone task }
else { # perform some other task}

more info on msdn

18 October 2016

Get computer manufacturer and model

command prompt
wmic computersystem get model, manufacturer


powershell
Get-WmiObject Win32_ComputerSystem | Select-Object Manufacturer, Model


visual

msinfo32.exe