Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Tuesday, March 10, 2020

Generate random password in Powershell

$characters = 'abcdefghkmnprstuvwxyzABCDEFGHKLMNPRSTUVWXYZ'
$nonchar = '123456789!$%&?+#'
$length = 15  #The total length will be 15, the last two characters are nonchar.

# select random characters
$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
$random2 = 1..2 | ForEach-Object { Get-Random -Maximum $nonchar.length }

$private:ofs= ""
$password = [String]$characters[$random] + [String]$nonchar[$random2]
return $password

Wednesday, January 22, 2020

Get list of un protected OU's

To get locating OUs that isn't protected from accidental deletion in AD

Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {$_.ProtectedFromAccidentalDeletion -eq $false}

Thursday, August 15, 2019

Move members of group to another OU

$OU = "OU=Users,OU=Test,DC=test,DC=com"
Get-ADGroupMember -Server test.com -Identity 'probation-'test-group' | foreach { Move-ADObject -server test.com -Identity $_.DistinguishedName -TargetPath $OU}

Tuesday, January 8, 2019

Remove Computers from txt list powershell

Import-Module ActiveDirectory
$PCs = Get-content c:\tmp\fordisable.txt
foreach ($PC in $PCs)
{
Remove-ADComputer -server test.local -identity $PC -confirm:$false
}

Wednesday, May 30, 2018

Export File server Permissions to CSV

Export share folder Permissions to CSV file using powershell:


 $FolderPath = dir -Directory -Path "\\sharefolderPath" -Recurse -Force
 $Report = @()
 Foreach ($Folder in $FolderPath) {
     $Acl = Get-Acl -Path $Folder.FullName
     foreach ($Access in $acl.Access)
         {
             $Properties = [ordered]@{'FolderName'=$Folder.FullName;'AD
 Group or
 User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
             $Report += New-Object -TypeName PSObject -Property $Properties
         }
 }
 $Report | Export-Csv -path "C:\tmp\FolderPermissions.csv"

Monday, May 21, 2018

Reset password to all users in OU


Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=Users,OU=test,DC=test,DC=local" -Server test.local|   Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "pass-123" -Force)

Monday, March 26, 2018

Password Expiry Email Notification

$smtpServer="email.yourserver.com"
#When the expirary date is less than the number below, the user will be notified
$expireindays = 10
$from = "Company Administrator <msadminis@yourserver.com>"
$logging = "Enabled" # Set to Disabled to Disable Logging
$logFile = "C:\tmp\passwordlog.csv" # ie. “c:\mylog.csv”
$testing = "Disabled" # Set to Disabled to Email Users
$testRecipient = "administratorsmail@yourserver.com"
#############################################################
# Check Logging Settings
if (($logging) -eq "Enabled")
{
    # Test Log File Path
    $logfilePath = (Test-Path $logFile)
    if (($logFilePath) -ne "True")
    {
        # Create CSV File and Headers
        New-Item $logfile -ItemType File
        Add-Content $logfile "Date,Name,EmailAddress,DaystoExpire,ExpiresOn,Notified"
    }

} # End Logging Check

# System Settings

$textEncoding = [System.Text.Encoding]::UTF8

$date = Get-Date -format ddMMyyyy
# End System Settings
# Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired

Import-Module ActiveDirectory

$users = get-aduser -searchbase "OU=users,DC=yourserver,DC=com" -Server yourserver.com  -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }

$DefaultmaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
# Process Each User for Password Expiry
foreach ($user in $users)

{
    $Name = $user.Name

    $emailaddress = $user.emailaddress

    $passwordSetDate = $user.PasswordLastSet

    $PasswordPol = (Get-AduserResultantPasswordPolicy $user)

    $sent = "" # Reset Sent Flag

    # Check for Fine Grained Password

    if (($PasswordPol) -ne $null)

    {

        $maxPasswordAge = ($PasswordPol).MaxPasswordAge

    }

    else

    {

        # No FGP set to Domain Default

        $maxPasswordAge = $DefaultmaxPasswordAge

    }

    $expireson = $passwordsetdate + $maxPasswordAge

    $today = (get-date)

    $daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days

     

    # Set Greeting based on Number of Days to Expiry.

    # Check Number of Days to Expiry

    $messageDays = $daystoexpire



    if (($messageDays) -gt "1")

    {

        $messageDays = "in " + "$daystoexpire" + " days."

    }

    else

    {

        $messageDays = "today."

    }

   # Email Subject Set Here

    $subject="Your password will expire $messageDays"
    # Email Body Set Here, Note You can use HTML, including Images.

    $body ="

    Dear $name,

    <p> Your Password will expire $messageDays<br>

    To change your password on a PC press CTRL ALT Delete and chose Change Password <br>

<p> If you are using a MAC you can now change your password via Web Mail. <br>
    Login to <a href=""https://email.yourserver.com/owa"">Web Mail</a> click on Options, then Change Password.
    <p> Don't forget to Update the password on your Mobile Devices as well!
    <p>Thanks, <br>
    </P>
    IT Support
    <a href=""mailto:support@yourserver.com""?Subject=Password Expiry Assistance"">support@yourserver.com</a> | 1818
    <p>Thanks, <br>

    </P>"

 

    # If Testing Is Enabled - Email Administrator

    if (($testing) -eq "Enabled")

    {

        $emailaddress = $testRecipient

    } # End Testing



    # If a user has no email address listed

    if (($emailaddress) -eq $null)

    {

        $emailaddress = $testRecipient 

    }# End No Valid Email



    # Send Email Message

    if (($daystoexpire -ge "0") -and ($daystoexpire -lt $expireindays))

    {

        $sent = "Yes"

        # If Logging is Enabled Log Details

        if (($logging) -eq "Enabled")

        {

            Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$sent"

        }

        # Send Email Message

        Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $textEncoding 



    } # End Send Message

    else # Log Non Expiring Password

    {

        $sent = "No"

        # If Logging is Enabled Log Details

        if (($logging) -eq "Enabled")

        {

            Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$sent"

        }     

    }

 

} # End User Processing

Monday, February 26, 2018

Re-join Domain Without Restarting

“The trust relationship between the workstation and the primary domain failed”.

to fix this without restart


use this powershell command :

CD C:\Windows\System32\WinddowsPowershell\v1.0

Test-ComputerSecureChannel –credential Yourdoamin\Administrator –Repair

Enter admin password

to test relation ship use :

Test-ComputerSecureChannel 

If True - it works !!!


Friday, February 9, 2018

Get proxy settings using PowerShell

Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' `| Select-Object *Proxy*

Wednesday, December 6, 2017

Clear IIS logs using powershell script

get-childitem -Path c:\inetpub\logs\logfiles\w3svc*\*.log -recurse |
where-object {$_.lastwritetime -lt (get-date).addDays(-30)} |
Foreach-Object { del $_.FullName }

Friday, November 10, 2017

ADD extensionAttribute

If you have different upn names , than your domain server name and you need to use different upn-s for ldap queris you can add sammaacountname + server domain name to custem attributes.

In file atribute.txt write users sammaccountnames.

Import-Module ActiveDirectory
$Users = Get-Content c:\tmp\atribute.txt
ForEach ($User in $Users) {
$username = Get-ADUser -Server test.local -Identity "$user" -Properties  samaccountname |select -ExpandProperty samaccountname
Set-ADUser -Server test.local -Identity "$user" -Add @{extensionAttribute13="$Username@test.local"}
}

Wednesday, September 6, 2017

Exchange 2010: can’t remove move request – Failed to communicate with the mailbox database

After a failed move request, the mailbox is still marked is being moved and cannot be removed again

After a failed move request, sometimes (for unknown reason) the mailbox is still marked is being moved and cannot be removed again... the mailbox is shown with a green icon on the EMC (Exchange Management Console), however it cannot be seen on the "Move Request" section or with Get-MoveRequest command and cannot be cleared with the Remove-MoveRequest command.


1. Open User Attributes
2. Scroll down the attributes and search for an entry called "msExchMailboxMoveTargetMDBLink" and "msExchMailboxMoveBatchName".
5. Click on the "Edit" button.
6. Click on the "Clear" button.
7. Click the "OK" button.

If you have many users you can use powershell script:


$Users = Get-Content c:\tmp\atribute.txt

ForEach ($User in $Users) {

Set-ADUser -Server test.local -Identity "$user" -Clear "msExchMailboxMoveTargetMDBLink"
}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$Users = Get-Content c:\tmp\atribute.txt

ForEach ($User in $Users) {

Set-ADUser -Server test.local -Identity "$user" -Clear "msExchMailboxMoveBatchName"
}
in c:\tmp\atribute.txt put user DN-s.

After this you can remove failed moves from exchange console.

Tuesday, March 21, 2017

Reset Ad user password in OU

Reset Active Directory multiple users password in OU using powershell:

# Specify the OU.
$OU = [ADSI]"LDAP://ou=West,dc=MyDomain,dc=local"

# Enumerate all objects in the OU.
$arrChildren = $OU.Get_Children()
ForEach ($User In $arrChildren)
{
    # Only consider user objects.
    If ($User.Class -eq "user")
    {
        # Set password.
        $User.Invoke("SetPassword""123-zxc")
        # Expire the password.
        $User.pwdLastSet = 0
        $User.SetInfo()
    }
}

Saturday, February 25, 2017

Change msRTCSIP-GroupingID for multiple users

If you want In your organization to separate several Organizations from seeing each other.
You must set OU GUID  to msRTCSIP-GroupingID attribute.

After getting the OU ObjectGUID we set this GUID as the msRTCSIP-GroupingID option for all users in that OU.

to do this using powershell for multiple users:

copy OU ObjectGUID.
for example: 2DCF9FC8-CB7C-4382-AA97-EF9B890B9B6A

copy this GUID and convert this GUID to Hexadecimal

use this site:
http://www.windowstricks.in/online-windows-guid-converter

after converting we'll have C89FCF2D7CCB8243AA97EF9B890B9B6A

change this format to xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

C89FCF2D-7CCB-8243-AA97-EF9B890B9B6A


first import the AD PowerShell Module:

Import-Module ActiveDirectory

$Users = Get-Content c:\tmp\atribute.txt

ForEach ($User in $Users) {

Set-ADUser -Server test.local -Identity "$user" -replace @{'msRTCSIP-GroupingID'=[GUID]("C89FCF2D-7CCB-8243-AA97-EF9B890B9B6A")}
}


Friday, February 24, 2017

Add extensionAttribute for multiple users



To Add extensionAttribute :

Import-Module ActiveDirectory

$Users = Get-Content c:\tmp\atribute.txt

ForEach ($User in $Users) {

Set-ADUser -Server test.local -Identity "$user" -Add @{extensionAttribute1="test"}

}


To Remove extensionAttribute :


$Users = Get-Content c:\tmp\atribute.txt

ForEach ($User in $Users) {

Set-ADUser -Server test.local -Identity "$user" -Clear "extensionattribute1"

}

Monday, January 23, 2017

Powershell script to get users logged in in last 30 days

Powershell script to get users logged in in last X days

get-aduser -filter {lastlogondate -gt "8/1/2013"} -Properties lastlogondate | select Name,LastLogonDate | sort name


(get-aduser  -server contoso.com -filter {lastlogondate -gt "8/1/2013"} -Properties lastlogondate).count

Friday, November 4, 2016

Install Failover IIS Cluster using Powershell

   Check installed rolles NLB and IIS
Get-WindowsFeatute -name NLB,web-server

  Install roles web server and nlb on 3 servers from 1 console:
Invoke-Command –ScriptBlock {Add-WindowsFeature –Name NLB, web-server,wb-asp-net,webapp-dev,Web-ISAPI-Filter -IncludeManagementTools} –Computername iis01,iis02,iis03

  Create Nlb Cluster:
New-NlbCluster –hostname iis03 –OperationMode Multicast –ClusterName nlb01 –InterfaceName ethernet0 –ClusterPrimaryip 192.168.128.50 –SubnetMask 255.255.255.0

  Show NLB cluster
Get-NLBcluster –hostname iis03
$NLB= Get-Nlbcluster –hostname iis03

  ADD nodes to NLB cluster :
Add-NlbClusterNode –InputObject $Nlb –NewNodeName iis01 –newNodeInterface Ethrnet0
Add-NlbClusterNode –InputObject $Nlb –NewNodeName iis02 –newNodeInterface Ethrnet0

  Open TCP 80 port on firewall :
Set-NlbClusterPortRule –HostName iis03 –NewStartport 80 –NewEndPort 80

  ADD Dns record for cluster name :

Add-DnsServerResourceRecordA –ZoneName corp.local –Name nlb01 –Ipv4address 192.168.128.50

Tuesday, July 19, 2016

Remove Windows Failover Cluster

Run powershell as an administrator
Import-Module FailoverClusters
then clear-clusternode
run this commands on all nodes.

Remove Windows Failover Cluster

Run powershell as an administrator
Import-Module FailoverClusters
then clear-clusternode
run this commands on all nodes.

Tuesday, March 1, 2016

Loged on users on Remote computer powershell script

# Attempt to get the user
$cred = Get-Credential

Get-Content "C:\tmp\computers.txt" | %{
  Get-WMIObject Win32_ComputerSystem -Impersonation 3 -Credential $cred -ComputerName $_ -ErrorVariable WMIError -ErrorAction SilentlyContinue

  # If WMIError has a value an error occurred. Create an object holding
  # the Computer Name and an empty Username property for the output
  If ($WMIError) { $_ | Select-Object @{n='Name';e={ $_ }}, Username }
} | Select-Object Name, @{n='Username';e={ $_.Username -Replace ".*\\" }} | Export-CSV "C:\tmp\output.csv"