Search This Blog

Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Thursday, June 14, 2012

Press any key to continue using Powershell

Hi,

This is the code in powershell that can be used as function where you want to repeat the tasks or present user with some kind of choice.

 

# Clear screen to clear the trash off the screen
clear-host


# Using here string to display Menu
$menu = @"
Menu
--------------------
Select your options
1
2
3
4
5
6
7
8
0 : Press 0 to Exit

"@

write-host $menu
Function Pause ($Message = "Press any* key to continue . . .Well I don't mean all :) ") {
    If ($psISE) {
        # The "ReadKey" functionality is not supported in Windows PowerShell ISE.

        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)

        Return
    }

    Write-Host -NoNewline $Message
   
    # Secret codes :) you don't want to continue when press shift key alt etc etc
   
    $Ignore =
        16,  # Shift (left or right)
        17,  # Ctrl (left or right)
        18,  # Alt (left or right)
        20,  # Caps lock
        91,  # Windows key (left)
        92,  # Windows key (right)
        93,  # Menu key
        144, # Num lock
        145, # Scroll lock
        166, # Back
        167, # Forward
        168, # Refresh
        169, # Stop
        170, # Search
        171, # Favorites
        172, # Start/Home
        173, # Mute
        174, # Volume Down
        175, # Volume Up
        176, # Next Track
        177, # Previous Track
        178, # Stop Media
        179, # Play
        180, # Mail
        181, # Select Media
        182, # Application 1
        183  # Application 2

    While ($KeyInfo.VirtualKeyCode -Eq $Null -Or $Ignore -Contains $KeyInfo.VirtualKeyCode) {
        $KeyInfo = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
    }

    Write-Host
}


# using do while loop to do switch case annoyance

do {

if($a)
 {
    clear-variable a
  }
$a = read-host "Select your option"

switch ($a)
    {
      
        1 {write-host -ForegroundColor RED "The color is red."; Pause;}
        2 {write-host -ForegroundColor DARKBLUE "The color is blue."; Pause;}
        3 {write-host -ForegroundColor GREEN "The color is green."; Pause;}
        4 {write-host -ForegroundColor YELLOW "The color is yellow."; Pause;}
        5 {write-host -ForegroundColor DarkYellow "The color is orange."; Pause;}
        6 {write-host -ForegroundColor Magenta "The color is purple."; Pause;}
        7 {write-host -ForegroundColor Cyan "The color is pink."; Pause;}
        8 {write-host -ForegroundColor Gray "The color is brown."; Pause;}
        0 {write-host "Exiting..."; Exit;}
  default {"The color could not be determined."; Pause;}
     }
    }
     while(!($a -eq 'null'))

 

Hope this will be helpfully in some ways.

Regards,

Navdeep [v-2nas]

www.ExchangeADTech.com

Friday, August 5, 2011

Appending members to Existing Group’s Membership

Hi All,

I got a request from my old good friend. He has contacts which are member of various groups and now this contact’s group membership needs to be added to another Group membership.  There are about 40k contacts how to do this using powershell script and without overwriting the group’s existing membership. So here how we did it.
I used questad cmdlets with powershell.

Get-QadObject -identity Contact | Get-QADMemberOf | Add-QADGroupMember -identity Group

With the help of Quest the code has been made really really short. Although the same could have been done using pure powershell but it would require some grey matter which is in short :)

Monday, May 9, 2011

PowerShell Script to update metadata of MP3 files

Recently I have downloaded over 100 mp3 narrations on Pastimes and Activities of Supreme Personality of Godhead. However these mp3 files have a generic filename i.e. canto_chapter_index name. Now when load it my iPhone i would see the names as title and there is no why to tell which no. describes which pastime. So i googled for a while and yes got few tips and created following PS script. The script reads csv file with corresponding title and based on actual name match found it updates the title of the file, also writes Artist and Album metadata. For this script you need .netframework library called TagLib.

*****************************************************
$TagLib = "D:\Temp\taglib-sharp-2.0.4.0-windows\Libraries\taglib-sharp.dll"

[System.Reflection.Assembly]::LoadFile($TagLib) | Out-Null

$KrsnaBook = import-csv C:\Users\user\Downloads\KrsnaBook.csv

cd C:\Users\user\Downloads\Krsna


foreach($fileName in Dir)
{
Foreach($Name in $KrsnaBook)
{

if($fileName.Name -eq $Name.Name)
{

Write-Host $Name.Title
$Media = [TagLib.File]::Create("C:\Users\user\Downloads\Krsna\" + $fileName.Name.ToString())
$Media.Tag.Title = $Name.Title
$Media.Tag.Artists = "Srila Prabhupada"
$Media.Tag.Album = "Krsna Book"
$Media.Save()
}

}
}
**********************************************

So now you can also use the the above ps code to update titles based on the filename.

Navdeep

Monday, March 14, 2011

Displaying Folder/Sub Folder Permission and Inheritance


Hi All,

How to quickly check where inheritance is messed up and who has what permission on different level in Folder Structure.

If just want to check on Single file or Folder use the following command
Get-Acl -Path C:\windows | FL Path, AccessToString


For Bulk use this
Now run the following command to get folder path

get-childitem P:\folderName -recurse | foreach {$_.directoryName} | Get-Unique

You can either copy from the console or redirect it to a csv file

get-childitem P:\folderName -recurse | foreach {$_.directoryName} | Get-Unique | Out-File -FilePath P:\Temp\inheritance.txt

Open the File, Add FolderName (can be anything) as header, rename the extension to .csv

Now

import-csv -path P:\temp\inheritance.csv | %{Get-Acl $_.FolderName} | FT Path,
AreAccessRuleProtected, AccessToString -Wrap

Monday, January 17, 2011

PowerShell Script To Create OU Structure and Test Users for Lab Env

Hi All,

The following is the powershell code to create test users and default ou structure. It's quite basic script. But works wells. Requires little modification. However if you like you can put various controls and make it more intelligent. I will try to put more controls latter but right now it just serves the purpose for which i created this script.

################################
#PowerShell Script To Create OU Structure and Test Users for Lab Env
# By v-2nas v 0.1
################################
Clear
$StrOUName = Read-Host "Enter SiteName for Creating Default Organizational Unit (OU) Structure"
$objDomain = [ADSI]"ldap://dc=brs,dc=glk,dc=net/"
$objOU = $objDomain.Create("OrganizationalUnit", "OU=" + $StrOUName)
#$objOU = $objDomain.Create("OrganizationalUnit", "ou=" + $StrOUName)
$objOU.SetInfo()
Write-Host $StrOUName  "OU Has Been Created."
write-host "Now creating Default OU Structure........."

#### Default OU Structure
$objDomain1 = [ADSI]"ldap://ou=$StrOUName,dc=brs,dc=glk,dc=net/"
$objOu1 = $objDomain1.Create("OrganizationalUnit", "ou=" + "Accounts")
$objOu1.SetInfo()
$objDomain2 = [ADSI]"ldap://ou=$StrOUName,dc=brs,dc=glk,dc=net/"
$objOu2 = $objDomain2.Create("OrganizationalUnit", "ou=" + "Computers")
$objOu2.SetInfo()
$objDomain3 = [ADSI]"ldap://ou=Accounts,ou=$StrOUName,dc=brs,dc=glk,dc=net/"
$objOu3 = $objDomain3.Create("OrganizationalUnit", "ou=" + "Users")
$objOu3.SetInfo()
$objDomain4 = [ADSI]"ldap://ou=Accounts,ou=$StrOUName,dc=brs,dc=glk,dc=net/"
$objOu4 = $objDomain4.Create("OrganizationalUnit", "ou=" + "Groups")
$objOu4.SetInfo()
$objDomain5 = [ADSI]"ldap://ou=Computers,ou=$StrOUName,dc=brs,dc=glk,dc=net/"
$objOu5 = $objDomain5.Create("OrganizationalUnit", "ou=" + "MemberServer")
$objOu5.SetInfo()
$objDomain6 = [ADSI]"ldap://ou=Computers,ou=$StrOUName,dc=brs,dc=glk,dc=net/"
$objOu6 = $objDomain6.Create("OrganizationalUnit", "ou=" + "Workstation")
$objOu6.SetInfo()
Write-Host "Creating Test User Account......"
# Create Users
$users = import-csv usersData.csv
$container = [ADSI] "ldap://OU=Users,ou=Accounts,ou=$StrOUName,dc=brs,dc=glk,dc=net/"
$users | foreach {
    $UserName = $_.UserName
    $newUser = $container.Create("User", "cn=" + $UserName)
    $newUser.Put("sAMAccountName", $UserName)
    $newUser.SetInfo()
    $newUser.psbase.InvokeSet('AccountDisabled', $false)
    $newUser.SetInfo()
    $newUser.SetPassword("xxxxx")
 $newUser.put("description","Test User Account for lab testing")
 $newUser.put("givenName", $userName)
 $newUser.SetInfo()
}

Friday, November 26, 2010

Binding a user to ADSI to get all attributes

 $objdomain = New-Object System.Directoryservices.DirectoryEntry
 $searcher = New-Object system.directoryservices.directorysearcher
 $searcher.SearchRoot = $objdomain
 $searcher.filter = "(&(objectcategory=user)(samaccountname=singhn))"
 $userobj = $searcher.findone()
 $u = $userobj.getdirectoryentry()
 $u | fl

Monday, November 15, 2010

Automatic Folder Creation for QTrees

Hi,

Following is the script which takes desired folder name as input and then create folder structure.

The content of folder.txt shud be like this

P:\ManagedFolder\Temp\1
P:\ManagedFolder\Temp\1\7
P:\ManagedFolder\Temp\1\8
P:\ManagedFolder\Temp\1\9

Level0Folder\Level1Folder\Level2Folder\

It will create the required folders automatically
****************************************************
$FolderList =Get-Content P:\ManagedFolder\Temp\folder.txt

foreach ($folderName in $folderList)
{

write-host $folderName

if(Test-Path $folderName) {
write-host -ForegroundColor Red "$folderName" folder already exists in the given location
}
else {

write-host creating folder "$foldername"
New-Item "$foldername" -type Directory

}
}
****************************************

For creating  shares following code can be used
$objwmi = [WmiClass] 'win32_share'
$objwmi.create($foldername,$sharename,0)

Regards,
Navdeep aka v-2nas

Sunday, October 31, 2010

Script to find users in Domain

Well it's challenging to write scripts because of not a main stream scripter but it's fun
So here is the latest script to find users in specific ou and retrieve their specific properties.

$strFilter ="(&(objectclass=user)(objectCategory=person))"
$objOU = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=Privileged Accounts,OU=User Accounts,DC=govinda,DC=com")
$objSearcher = New-object System.DirectoryServices.DirectorySearcher

$objSearcher.SearchRoot = $objOU
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$objSearcher.PropertiesToLoad.Addrange(@("sAMAccountName","employeeid","name"))
      

$colResults=$objSearcher.FindAll()

# Data Format in List

foreach($objResult in $colResults)
       { $objItem = $ObjResult.Properties;
         "Name: " + $objItem.name;
         "sAMAccountName: " + $objItem.samaccountname;
         "employeeID: " + $objItem.employeeid;
          write-host ************************
       }

# Data Format in Table
$colResults | FT @{label="Name";Expression={$_.Properties.name}},@{label="sAMAccountName";Expression={$_.Properties.samaccountname}},@{label="EmployeeID";Expression={$_.Properties.employeeid}}

Tuesday, October 26, 2010

Script to find folder size

We are doing home drive migration project where in we need to find out what is the size of users' home drive. To make this task more efficient and fast we used powershell to achieve this. Small code but works great


param([string]$path)
# declaring the parameter so we can invoke parameter at command line


write-host size of $path is
# just info


$colItems = (Get-ChildItem $path -recurse | Measure-Object -property length -sum)
# *get-childItem will get all the folders and files under given path, recurve will check for subfolder and files, then pipe to measure object which will sum all the size *#


"{0:N2}" -f ($colItems.sum / 1MB) + " MB"
# 0:N2 will parse the data to two decimal place, and then format from bytes to MB.


The script can be used like this
>.\foldersize.ps1 "\\ServerName\Share$"

Monday, September 27, 2010

Script to Check Inheritable Permission and set them

Scenario: AdminSDHolder is busted and this has caused inhertiable permissions to be broken causing GPO issues. Now who gonna check all the inhertiable permission 1 x 1 ... well with the help of powershell we have achiceved that...

## sets the "Allow inheritable permissions from parent to propagate to this
##object"check box
# Contains DN of users
$users = Get-Content C:\C:\Navdeep_DoNotDelete\variables\users.txt

ForEach($user in $users)
{
# Binding the users to DS
$ou = [ADSI]("LDAP://" + $user)
$sec = $ou.psbase.objectSecurity
if ($sec.get_AreAccessRulesProtected())
   {
   $isProtected = $false ## allows inheritance
   $preserveInheritance = $true ## preserver inhreited rules
   $sec.SetAccessRuleProtection($isProtected, $preserveInheritance)
   $ou.psbase.commitchanges()
   Write-Host "$user is now inherting permissions";
   }
else
   {
    Write-Host "$User Inheritable Permission already set"
   }
   }

Code to give member count of a Group

Scenario: Member count is required for approval for granting mass mailing rights to user.
So far vb script has been used to do this job when SysAdmin needs to manually add the dn of the group and run the script however they can now use a small PS code to do the same task more effectively

(Get-Group -Identity medstaff_sender).members | measure-object name or

(Get-Group -Identity medstaff_sender).members |  foreach($count++) | $count

Then $count for the no. of members.

Cheers !!!

Friday, September 24, 2010

Script to make users member of a new group

Senario:
GroupTestA has 2000 members which needs to be added to another new group GroupTestB. There is no group nesting.

*The script will work only when there are no members present in new group otherwise script fails. I haven't added thelogic where it checks for member present in both groups and skip them.

$root = [adsi]""
$rootdn = $root.distinguishedName
#Bind to the First Group DN

$groupTA = [adsi]("ldap://CN=GroupTestA, OU=Testing OU," + $rootdn)
$GroupMembers = $groupTA.member

#Bind to Second Group DN
$groupTB = [adsi]("ldap://CN=GroupTestB, OU=Testing OU," + $rootdn)
foreach($dn in $groupMembers)
{
$groupTB.member.add($dn)
}
$groupTB.Setinfo()

************************
Just created one with logic. It works well and tested ok but it throws exception.....
# Logic to skip the common members and add only unqiue members

foreach($dnA in $groupMembersA)
{
 foreach($dnB in $groupMembersB)
{
 if($dnA -ne $dnB) {
 write-host $dnA -ForegroundColor GREEN
$groupTB.member.add($dnA)
 $groupTB.Setinfo()
}
else {
write-host $dnB -foregroundcolor RED
}
 }
 }
************************************************