Archive | PowerShell RSS feed for this section

PowerShell replace text in files

In the example I am replacing every .html file in the folder that has my line of
the words ‘old Text’ and replacing with words ‘new TeXT’ *(using Power Shell to replace strings)

You can change the file extension and update the location path to a single file to replace text in one file only.

 get-childItem 'C:\scripts\*.txt' -recurse | ForEach {
(Get-Content $_ | ForEach {$_ -replace 'OLD TeXT', ' NEW TeXT'}) | 
Set-Content $_ 
}
0 Comments

PowerShell Windows 2012 R2 IIS FTP web user creation

( if you want FTP folder isolation for local users on  Windows Server 2012 r2 Setup read : https://community.rackspace.com/products/f/25/t/491

Windows 2012 r2 PowerShell Task: Uses PowerShell

  LOCAL USER CREATION TASKS
    • PowerShell Create Local user account
    • PowerShell Set description on account to reflect day activated
    • PowerShell  Set Password to never expire / user cant change password
    • PowerShell Create  IIS website VirtualDirectory  IIS:\Sites\ (IIS 7, IIS 7.5
    • PowerShell Create  users folder in FTProot IIS
    • PowerShell Create FTP directory IIS
    • PowerShell Create user permissions ACL  ( Adds user to folder / Access = modify)
    •  PowerShell Create local group membership to FTP Group
  • PowerShell  use Web Administration module
    #########################
    # #windows 2012 R2 create FTP 2012r2, IIS 2012 R2
    # Description:www.BrilliantlyEasy.com import
    # Create local users for FTP
    # ######## Create HTML URL Links
    # Add user to local FTP #
    # Make edies to someUser,SomePassword,SomeComputer
    #####################################<
    Import-Module WebAdministration
    Write-Host -foregroundcolor Yellow 'Admin Privileges Required!'
    #create local user
    $accountName = 'someUser'
    $password = 'somePassword'
    $day = get-date -format "MM.dd.yyyy"
    $description = "$day account activated"
    $computer = [ADSI]"WinNT://$env:computername,computer"
    $user = $computer.Create("user", $accountName)
    $user.SetPassword($password)
    $user.SetInfo()
    $user.Description = $description
    $user.SetInfo()
    $user.userflags = 65536 -bor 64 #user cant change / never expire
    $user.SetInfo()
    $ServerName = 'someComputerName'
    $group = [ADSI]"WinNT://$ServerName/FTP USER"
    $group.add("WinNT://$ServerName/$accountName") ;
    #END create local user
     #create users web directory publish folder
    New-Item -path C:\inetpub\ftproot\Localuser `
    -name $accountName -type directory
    Start-Sleep -Seconds 3
    New-Item "IIS:\Sites\Default Web Site\$accountName" `
    -type VirtualDirectory -physicalPath C:\inetpub\ftproot\Localuser\$accountName
    
     #this function sets access rules for user
    Function Acl-Rule
    {
    #target folder that needs security rules added
    $target = "C:\inetpub\ftproot\Localuser\" + $accountName
    $mydir = get-acl $target
    #allow the proper account Modify control from $account
    $rule = new-object system.security.accesscontrol.filesystemaccessrule`
     ($accountName,"Modify", "containerinherit,objectinherit","none","allow")
    #Add the access rule to be applied later
    $mydir.addaccessrule($rule)
    #}
    #apply all access rules to target directory
    set-acl $target $mydir
     }#end function
    
     Acl-Rule
     }
    #END
1 Comment

PowerShell List OU

PowerShell List All OUs – organizational units in your domain. Very handy if you need to print out your OU list or make use of it in a different script.


#LDAP://localhost/DC=YOUR_DC,DC=YOUR_COMPUTER
$Connect = "LDAP://localhost/DC=brilliantly,DC=easy"
$ads = [adsi] $Connect
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"")
$ads.PageSize = 25000
$ads.Filter = "(&(objectCategory=OrganizationalUnit))"
$ads.SearchScope = "Subtree"
$ads.PropertiesToLoad.AddRange(("canonicalName".split()))
$ads.FindAll() | foreach { $_.properties.canonicalname } | sort

Result:.\list_ALL_OU_Doamin.ps1

brilliantly.com/Domain Controllers
brilliantly.com/IT Virtual Classroom Accounts
brilliantly.com/IT Virtual Classroom Accounts/Students

0 Comments

PowerShell – very simple for loop that takes a less than count, sending text to screen

Powershell :  write-output and pipe | it to a file similar to

| Out-File $pathName + “SomeFile.txt”) .

######################################
#Author: www.BrilliantlyEasy.com"
#Send some text to screen and Make it color
#Print out accounts for users
##################################################
## For loop does for count from 300-401
For ($i=300; $i -lt 401; ){

$a= $i++

#COLOR MAKER: -foregroundcolor red -backgroundcolor yellow
write-host "Site Name" -foregroundcolor red -backgroundcolor yellow
#notice $a and the `b -`b moves back one char.
write-host "http://www.BrilliantlyEasy.com"`b$a
###############################notice $a
write-host "UserLogin: easy\user"`b$a
write-host "UserName: user"`b$a
write-host " "

}
0 Comments

PowerShell import-CSV create new file type HTML using group membership

PowerShell Task:

  • Import CSV
  • Read import-csv line by line
  • Match Non AD group To a users folder
  • Create an HTML page from powershell
  • Create a hyper link in each folder from  PowerShell
  • base membership from a non AD source.

The task was to use a CSV file from an outside source that would create an HTML page with its HTML link based on the content of import-csv file.
The group member ships in the CSV file did not come from  AD but based on a directory structure

#########################
#########################
# //===Name: .\easy_ImportCsv.ps1
# Description:www.BrilliantlyEasy.com import
# from CSV export to HTML File by
#          a NoN AD group memberships
# ########    Create HTML URL Links
#By Group in user folders
#
#####################################</pre>
write-host $objItem.Name, $objItem.WorkingSetSize `

 -foregroundcolor "magenta"
#var for date/time
$datetime = get-date -format G

#Var $OFS used for new lines when using write-host
$OFS = "`r`n`r`n"
$OFS1 = "`n"

#Source of users

#var used for team memberships in import-csv
$Red = "Marketing"
$Green = "Sales"
$Blue= "Development"

write-host $OFS  $datetime $OFS1 `
"IMPORT FILE NAME: C:\scripts\powershell\portfoiloportStu.csv" `
-foregroundcolor "magenta" -backgroundcolor "yellow"
#import-csv "c:\import\accountsInfo.csv"

#Var for source of folder location

$source = "C:\users\folder"

#Var for CSV import of user files
$csv_info = Import-Csv C:\scripts\powershell\portStu.csv

foreach ($line in $csv_info)
{
#$destination = "C:\users\folder\" + $line.Username

#powershell create HTML file and HTML code content
# from a Variable with variables inside of HTML
#*look at the new-item -force -value $outFile
$outFile ='
<img alt="image" longdesc="image" width="846" height="62" />
<table style="width: 57%;">'$outFile =  $outFile +
 '$outFile =  $outFile + $line.Username
$outFile =  $outFile +  '
#Var that holds the full path to user GROUP & their User name
# powershell destination use path in a variable with quotes
#by use of + syntax
$destination = "C:\users\folder\"+$line.Group_Role+"\"+ '
$line.Username
#write-host "1" $($line.Username) $($line.Link) `
$($line.Group_Role)
#if red grab the user in Red Groupif  ($Red -eq $line.Group_Role)
{write-host "RED GROUP" $OFS1  $line.Username $line.Link
`$line.Group_Role#Powershell Create a new HTML  survey.html file
# using Variable  to spit out HTML
#code content based on CSV importnew-item -path $destination -name
survey.html -type file `-force -value $outFile}
#elseif red grab the user in
# Green Groupelseif ($Green -eq  $line.Group_Role)
{Write-Host "Green Group"     $OFS1  $line.Username $line.Link
`$line.Group_Rolenew-item -path $destination -name survey.html -type file
`-force -value $outFile}
#elseif red grab the user in Blue Groupelseif
 ($Blue -eq $line.Group_Role){Write-Host "Blue Group"
$OFS1  $line.Username $line.Link
`$line.Group_Role#Powershell Create a new HTML file  survey.html
#using Variable  to spit out HTML code content new-item -path
$destination -name survey.html -type
`file -force -value $outFile}else {"Users have been imported. "}}
#END
0 Comments

PowerShell set Satic IP DNS Gateway SubNet

PowerShell modification to Network adapter from script

Network Adapter Configuration

  •  set Satic IP
  • set SubnetMask
  •  set Gateway  
  • set DNS Server
#########################################################
##Author: brilliantlyeasy.com
#network_change.ps1
# modification to Network adapter -
##########################################################

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration |
 where{$_.IPEnabled -eq "TRUE"}
Foreach($NIC in $NICs) {
#change in quotes to yor ip address
#set static IP and Subnet
$NIC.EnableStatic("192.xxx.xxx.xxx", "255.255.255.0")
#set gateway
$NIC.SetGateways("192.XX.XX.XX")
#set DNS Servers
$DNSServers = "192.XX.XX.XX","192.XX.XX.XX"
$NIC.SetDNSServerSearchOrder($DNSServers)
$NIC.SetDynamicDNSRegistration("FALSE")
}

The above script can be handy when you need to set a number
of server IP addresses.
Example:
When a company decides to change entire address scheme
is implemented.

1 Comment

PowerShell remove character text from all files in a directory SED powershell operation

Powershell script to remove text from each file in a directory.
*In Linux-Unix SED works very well for this.

POWERSHELL “Sed like”

Using variables to recurse a directory cheating using set-content to work like
regular expression

#remove a character from all files in a directory -=
 #REMOVE
#var old is text to remove
 $old = ','
#var $new = the text you want to replace ( I am replacing text with
#      a blank space)
$new = ''
#change the Get-ChildItem to a folder or your choice
Get-ChildItem C:\scripts\files\ -Recurse | Where {$_ -IS [IO.FileInfo]} |

% {

(Get-Content $_.FullName) -replace $old,$new | Set-Content $_.FullName
 Write-Host "----- WORKING   ----------"
 Write-Host "Processed: " + $_.FullName

}
 #REMOVE DONE

—– WORKING ———-
Processed: + c:\scripts\files\.txt
Processed: + c:\scripts\files\file1.txt
Processed: + c:\scripts\files\txt-159_2-5.txt
Processed: + c:\scripts\files\extf\ile0_0_140-159_6-10.txt
Processed: + c:\scripts\files\extftxt60-179_11-15.txt
Processed: + c:\scripts\files\extftxt60-179_2-5.txt
Processed: + c:\scripts\files\extftxt60-179_6-10.txt
Processed: + c:\scripts\files\txt122-188_11-15.txt
Processed: + c:\scripts\files\txt122-188_2-5.txt
Processed: + c:\scripts\files\txt122-188_6-10.txt
Processed: + c:\scripts\files\txt120-139_11-15.txt
Processed: + c:\scripts\files\txt120-139_2-5.txt
Processed: + c:\scripts\files\txt120-139_6-10.txt
Processed: + c:\scripts\files\txt140-159_11-15.txt
Processed: + c:\scripts\files\txt140-159_2-5.txt
Processed: + c:\scripts\files\txt140-159_6-10.txt
Processed: + c:\scripts\files\txt160-179_11-15.txt
Processed: + c:\scripts\files\txt160-179_2-5.txt
Processed: + c:\scripts\files\txt160-179_6-10.txt

0 Comments

PowerShell Create OUs from an array

 PowerShell Create OUs organizational units in your domain from an array -
write-host "building OU for: $array"
$array = ("Human Resources","Purchasing",
"Production","Marketing","Information Technology","Sales","New York",
"Kansas City","Los Angeles","Building 125","Town Pavilion",
"Architecture","Center Square","925 Grand","WallStreet Tower")
#New-ADOrganizationalUnit -Name SOME+NAME -Path
#CHANGE OU/NAME /DC= to modify for DC
#"OU=NAME,DC=NAME,DC=NAME"
#build array and do it to it
#MAKE AN OU CALLED OU=buildings
#CHANGE OU/NAME /DC= to modify for DC
foreach ($item in $array)
 { New-ADOrganizationalUnit -Name $item
       -Path "OU=buildings,DC=brilliantly,DC=com"}

PS .\buildings_Create_OU.ps1

building OU for: Human Resources Purchasing Production Marketing
Information Technology Sales New York Kansas City Los Angeles
Building 125 Town Pavilion Architecture Center Square 925 Grand WallStreet Tower

PS C:\Users\adm-easy\Desktop\powershell\MOSES AD builder>

ou_create.png

0 Comments

PowerShell NotePad++ Dark Black theme syntax highlighting

I love notepad++ but hate the default white background.  This little install makes NotePad++ have a nice dark background with full syntax highlighting possible with powershell.

1. Delete DeepBlack theme: (C:\Program Files (x86)\Notepad++\themes\)

2. Download powershell updated DeepBlack Theme (Attached File: Deep Black theme with Powershell, sorted. ): http://sourceforge.net/tracker/index.php?func=detail&aid=3389453&group_id=95717&atid=612384

3. Add the downloaded XML to  (C:\Program Files (x86)\Notepad++\themes\)

(add to C:\Program Files (x86)\Notepad++\themes

*OLDER VERSION2. Download: http://poshcode.org/notepad++lexer/

Once downloaded,  unpack the zip and put all the files / folders into the Notepad++ Plugins folder

(add to C:\Program Files (x86)\Notepad++\plugins)

Special thanks: http://huddledmasses.org/using-notepad-plus-plus-for-powershell-editing/

3 Comments

WordPress PowerShell Syntax Highlighting how to

#PowerShell WordPress syntax Highlighting IT WORKS! 

1. Download http://wordpress.org/extend/plugins/syntax-highlighter/installation/
2. Go to wordpress–> plugins –>ADD NEW –> Chose File (u downloaded)–>  Install Now
3. The image with red marks shows syntax hightligher powershell open and close tag –

(It took me way to long to figure out what the start stop tags were

hence the image /photo on left  with red maker underling the CODE!

START TAG [
language="powershell" ]
foo script
[/code]
END TAG
#IT WORKS!
if ($c -eq "Cat")
 { $a="Bubble" }
 else
 { $a="Trouble" }
Write-Host $a
 [/code]
0 Comments