Showing posts with label technique. Show all posts
Showing posts with label technique. Show all posts

Saturday, March 7, 2009

import-csv



function get-currentScriptDir{

$b = & { $myInvocation.ScriptName }
#$b


# Write-Host '2d output'
$c = split-path $b


# Write-Host  'this is ' `t $c

return  $c

}

$d = get-currentScriptDir

$e = $d+'\testfile.txt'

Write-Host ' this is ' $e


$file2Chk = $d+'\testfile.txt'
$header = "Name","Department","Title"

Import-Csv $file2Chk -Header $header | foreach{

Write-Host $_.Name

}






http://www.scriptinganswers.com/forum2/forum_posts.asp?TID=2636
import-csv c:\tools\subnets.csv | foreach {

$sitename = $_.sitename
$subnetIP = $_.SubnetIP
$loc = $_.Location
$siteLink = $_.SiteLink

...
$link.save()

}


# http://www.leadfollowmove.com/archives/powershell/excel-powershell-and-the-import-csv-cmdlet
# http://www.leadfollowmove.com/archives/powershell/creating-groups-in-active-directory-with-powershell



# Constants from: http://msdn2.microsoft.com/en-us/library/aa772263.aspx
Set-Variable -Name ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP  -value 4      -option constant
Set-Variable -Name ADS_GROUP_TYPE_GLOBAL_GROUP      -value 2       -option constant
Set-Variable -Name ADS_GROUP_TYPE_LOCAL_GROUP      -value 4      -option constant
Set-Variable -Name ADS_GROUP_TYPE_UNIVERSAL_GROUP    -value 8       -option constant
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_ENABLED    -value -2147483648  -option constant
 
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_DOMAIN_LOCAL  `
  -value ($ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP  `
  -bor $ADS_GROUP_TYPE_SECURITY_ENABLED)  -option constant
 
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_DOMAIN_GLOBAL  `
  -value ($ADS_GROUP_TYPE_GLOBAL_GROUP  `
  -bor $ADS_GROUP_TYPE_SECURITY_ENABLED)  -option constant
 
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_UNIVERSAL  `
  -value ($ADS_GROUP_TYPE_UNIVERSAL_GROUP    `
  -bor $ADS_GROUP_TYPE_SECURITY_ENABLED)  -option constant
 
# ---------------------------------------------------------------------------------------------------
  
  # Bind to the root of the domain
  $root  = [adsi]""
  $rootdn  = $root.distinguishedname
 
# ---------------------------------------------------------------------------------------------------
function create-group
# ---------------------------------------------------------------------------------------------------
{
Param (
  $Location,
  $Group,
  $scope,
  $Description
  )
  # The domain DN is added so the OU location doesn't need to be a full DN  
  # This also doesn't tie you down to a specific Domain.
  $ou = [adsi]("LDAP://"+$Location+","+$rootDN)
  $newGroup = $ou.create("group", "cn="+$Group)
  $newgroup.put("sAmAccountName", $Group)
  $newGroup.Put("Description", $Description)
  
  switch ($scope)
  {
    "Security Domain Local"      {$Type = $ADS_GROUP_TYPE_SECURITY_DOMAIN_LOCAL}
    "Security Domain Global"    {$Type = $ADS_GROUP_TYPE_SECURITY_DOMAIN_GLOBAL}
    "Security Universal"      {$Type = $ADS_GROUP_TYPE_SECURITY_UNIVERSAL}
    "Distribution Domain Local"    {$Type = $ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP}
    "Distribution Domain Global"  {$Type = $ADS_GROUP_TYPE_GLOBAL_GROUP}
    "Distribution Universal"    {$Type = $ADS_GROUP_TYPE_UNIVERSAL_GROUP}
  }
  $NewGroup.put("grouptype", $Type)
  $newGroup.SetInfo()
}
 
# ---------------------------------------------------------------------------------------------------
 
# Create-Group "ou=Test OU" "Test Group" "Security Domain Local" "My Test Group"


$data = import-csv d:\coding\ps\groups.csv
foreach ($line in $data)
{
  write-host $line.GrpName $line.Desc $line.GrpType $line.DN
}


GrpName,Desc,GrpType,DN
Test Group1,PowerShell Test Group,Security Domain Local,"cn=users"




# PowerShell script create users in a named OU
# Author: Guy Thomas 
# Version 2.4 August 2008 tested on PowerShell v 1.0

$OuBorn = 'OU=PowerShell,DC=cp2,DC=mosel'
$Freshmen = 'E:\powershell\QAD\bunch4.csv'
import-csv $Freshmen |`
where {new-QADUser -ParentContainer $OuBorn `
-name $_.name -sAMAccountName $_.sAMAccountName `
; enable-QADUser $_.name }


# The Complete script looks like this : http://mow001.blogspot.com/2006/05/powershell-import-shares-and-security.html

# ImportShares.ps1  
# This script will Import the Shares from a CSV file   
# made by ExportShares.ps1 complete with securityInfo  
#   
# /\/\o\/\/ 2006      
# http://mow001.blogspot.com   

# Import the CSV file 

$ShareList = Import-Csv ShareInfo.csv 

# get the Unique Shares 

$sharelist | select -unique name,Path,Description |% { 

  $name = $_.name 
  $path = $_.Path 
  $description = $_.Description 
  "Processing : $name $path $description" 

  $sd = new-object system.management.managementclass Win32_SecurityDescriptor 
  $sd.DACL = @() 
  $ace = new-object system.management.managementclass Win32_ace 
  $Trustee = new-object system.management.managementclass win32_trustee 

  # Get all records in CSV file for the current share 

  $sharelist |? {$_.name -eq $name} |% { 

    # Convert SID to Binary version : 

    $sid = new-object security.principal.securityidentifier($_.sid) 
    [byte[]]$ba = ,0 * $sid.BinaryLength 
    $sid.GetBinaryForm($ba,0) 

    # Make Trustee Object 

    $Trustee.Domain = $_.Domain 
    $Trustee.get_Properties()['name'].set_Value($_.domain) 
    $Trustee.SID = $ba 

    # Make ACE Object 

    $ace.AccessMask = $_.AccessMask 
    $ace.AceType = $_.AceType 
    $ace.AceFlags = $_.AceFlags 
    $ace.trustee = $trustee.psobject.baseobject 
  
    # Add ACE to the DACL 

    $sd.DACL += $ACE.psObject.baseobject 
  } 

  $MC = new-object system.management.ManagementClass win32_share 
  $InParams = $mc.GetMethodParameters('Create') 

  # fill Parameters 

  $InParams["Access"] = $sd.PsObject.BaseObject 
  $InParams["Description"] = $_.Description 
  $InParams["Name"] = $_.name 
  $InParams["Password"] = [string] 
  $InParams["Path"] = $_.Path 
  $InParams["Type"] = 0 

  $R = $mc.InvokeMethod('Create', $inParams, $Null) 
  "Result : $($R.ReturnValue)" 
  
}



# You can use array slicing, get the rows from row 13 till the end of the file: http://en.wikipedia.org/wiki/Array_slicing#2006:_Windows_PowerShell


PS > $csv = get-content report.csv
PS > $csv[12..$csv.length] | out-file report1.csv 
PS > import-csv report1.csv  

Tuesday, February 10, 2009

Pinging a Server from a Server you are not logged in to

Pinging a Server from a Server you are not logged in to

So if you wanted server remote1 to ping server remote3 you could do something like this:


Get-WmiObject Win32_pingstatus –filter “Address =’remote3’” –computername remote1.| statuscode,address,_server

convert vbscript to powershell

Automating admin scenarios using PowerShell

Sunday, January 25, 2009

rename computer

Expert PowerShell advice and commentary from Dr. Tobias Weltner.

Function
 Rename-ComputerName ([string]$NewComputerName){ 

 
$ComputerInfo = Get-WmiObject -Class Win32_ComputerSystem 
$ComputerInfo.rename($NewComputerName) 
 
} 

This script shows you how to rename computer by using WMI

How to use it :

& .\rename-computerName.ps1

rename-computername "MyNewComputerNAME"

And to reboot you can use WMI class Win32_OperatingSystem and its method reboot():

$OS = Get-WmiObject -Class Win32_OperatingSystem

$OS.reboot()

OR

shutdown -r -t 10 -f -c "Restart OS"

Users of PowerShell V2 (currently CTP3) can use the Restart-Computer cmdlet too. :)

DETAILED DESCRIPTION

   The Restart-Computer cmdlet restarts the operating system on the local and remote computers.

   You can use the parameters of Restart-Computer to run the restart operations as a background job, to specify the authentication levels and alternate credentials, to limit the operations that run concurrently, and to force an immediate restart.

   This cmdlet does not require Windows PowerShell remoting unless you use the AsJob parameter.



Monday, December 22, 2008

Effective PowerShell from http://keithhill.spaces.live.com/

Effective PowerShell Item 1: The Four Cmdlets That are the Keys to Finding Your Way Around PowerShell, Effective PowerShell, 

Effective PowerShell Item 2: Use the Objects Luke. Use the Objects 

 Effective PowerShell Item 3: Know Your Output Formatters

 Effective PowerShell Item 4: Commenting Out Lines in a Script File

 Effective PowerShell Item 6: Know What Objects Are Flowing Down .the pipe

 Effective PowerShell Item 7: Understanding "Output"

Effective PowerShell Item 8: Output Cardinality - Scalars .

 Effective PowerShell Item 9: Regular Expressions 

 Effective PowerShell Item 10: Understanding PowerShell Parsing 

 

 

 

array compare

This article was Previously posted on Ying Li' 


$arrFirst = get-content First.txt
$arrSecond = get-content Second.txt

New-Item "C:\Myworkplace\ps\FirstInSecond.txt" -Type file
New-Item "C:\Myworkplace\ps\FirstNotInSecond" -Type file

Foreach ($First in $arrFirst)
{
If ($arrSecond -contains $First)
{Add-content "C:\Myworkplace\ps\FirstInsecond.txt" $First}
Else
{Add-content "C:\Myworkplace\ps\FirstNotInSecond.txt" $First}



===

PS> $a1 = 1,1,2
PS> $a2 = 1,2,1


You could force "sequence equality" by setting SyncWindow to 0:
Compare-Object $a1 $a2 -SyncWindow 0
 

Monday, December 15, 2008

snap-ins

To determine which snap-ins you can add to the standard Windows PowerShell console, type the following command at the command prompt:

Get-PSSnapin -Registered

to add a snap-in

add-pssnapin [-name]

To see the installed snapins use



Get-PSSnapin


Removes Windows PowerShell snap-ins from the current console.


Remove-PSSnapIn [-name]

Saturday, December 6, 2008

PowerShellASP


From their site: 
PowerShellASP is an ASP-like template language for Web Applications; templates contain a mixture of markup (HTML, XML or whatever you want to generate) and inline PowerShell code. At runtime, templates/pages are fully translated to PowerShell code and executed as a single unit inside a PowerShell pipeline, with the results sent to the client browser.
PowerShellASP runs off the ASP.NET platform, implemented as a custom IHttpHandler mapped to *.ps1x files. Because of this, you can mix PowerShellASP pages alongside any ASP.NET application. This provides a great way to leverage PowerShellASP inside your existing applications as needed or you can create complete applications from scratch based only on *.ps1x pages.

Wednesday, December 3, 2008

profile load issue solved

File C:\Users\Gaurav\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.
At line:1 char:2
+ .  <<<< ‘C:\Users\Gaurav\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1′
This is because PowerShell does not allow the execution of scripts by default. To fix this open PowerShell in Admin mode and set the execution policy to unrestricted by running the following command:

Set-ExecutionPolicy remotesigned
 
Notepad $profile 
Add-PSSnapin Quest.ActiveRoles.ADManagement
Set-ExecutionPolicy remotesigned

Saturday, November 22, 2008

error handeling

Trap [Exception] { “In PowerShell”

Catch-Error.ps1

 

#Requires -Version 2
# Show-TryCatchFinally.ps1
# Demonstrates try/catch/finally in V2
# First, try something that will work
Try {
$I=1
}
Catch {"Caught a problem in try 1"
}
Finally {
"All done with 1st try"
}

# Now try something that fails
$one=1
#$zero=0
Try { $one/$zero}
Catch {"Caught a problem in try 2"}
 

 


Default Error Handling
Error handling in PowerShell scripts
Lunch Lesson: Error Handling in PowerShell

Methods for handling errors in PowerShell can range from simple to complex

for each

  In PowerShell, foreach is both a statement and an alias to the ForEach-Object cmdlet. 

While you might think that both of these examples do exactly the same thing, they do not. 

Powershell tutorial 8 part 1

PowerShell tutorial 8 part 2

Essential PowerShell: Understanding foreach