Options

Script Repository

2»

Comments

  • Options
    JDMurrayJDMurray Admin Posts: 13,031 Admin
    Be sure to submit any public CVS or SVN repository created to: Add your code to Google Code Search


    I just discovered that Powershell files are not easy to find in Google CodeSearch. You need to search on the .ps1 file extension.
  • Options
    JDMurrayJDMurray Admin Posts: 13,031 Admin
    Oh, and if anyone wants to start a religious war over what is and isn't a scripting language, then I'm game! icon_lol.gif
  • Options
    PashPash Member Posts: 1,600 ■■■■■□□□□□
    Cheers undomiel I +1 ya. I may have use for this sort of thing currently.
    JDMurray wrote: »
    Oh, and if anyone wants to start a religious war over what is and isn't a scripting language, then I'm game! icon_lol.gif

    "My eyes! the goggles do noting!"

    But nah I am fine icon_lol.gif
    DevOps Engineer and Security Champion. https://blog.pash.by - I am trying to find my writing style, so please bear with me.
  • Options
    DevilWAHDevilWAH Member Posts: 2,997 ■■■■■■■■□□
    Aww it seems can't upload a excel sheet icon_sad.gif I was going to upload one that creates configs from a spread sheet data but oh well icon_sad.gif

    PS hope all are well, been some time since I posted but still haning in here, work been so busy but now back in to my CCNP so expect me here more now :)

    DevilWAH
    • If you can't explain it simply, you don't understand it well enough. Albert Einstein
    • An arrow can only be shot by pulling it backward. So when life is dragging you back with difficulties. It means that its going to launch you into something great. So just focus and keep aiming.
  • Options
    undomielundomiel Member Posts: 2,818
    Finally had a chance to write up a new script today. This is one that we've got set to fire off at midnight and configure per user's quotas based off their security group membership. This way the local admin just shuffles users between security groups rather than databases.
    param($TargetGroup = "", $WarningQuota = "", $SendQuota = "", $FinalQuota = "")
    
    # This script pulls all the mailboxes from an AD group and sets each user to the specified quotas
    # Usage is SetLevelLimits.ps1 -TargetGroup "Group Name" -WarningQuota 123 -SendQuota 456 -FinalQuota 789
    #
    # Note that limits are set in bytes
    
    # Open a remote session to the Exchange server
    $PowerSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.domain.local/PowerShell -Authentication Kerberos
    Import-PSSession $PowerSession
    
    $Group = Get-Group $TargetGroup
    
    # Loop through the group members and set their quotas then print out the mailbox and quotas for verification
    foreach($Mailboxes in $Group.Members)
    {
      Set-Mailbox $Mailboxes -IssueWarningQuota $WarningQuota -ProhibitSendQuota $SendQuota -ProhibitSendReceiveQuota $FinalQuota -UseDatabaseQuotaDefaults $false
      Get-Mailbox $Mailboxes | select Name,IssueWarningQuota,ProhibitSendQuota,ProhibitSendReceiveQuota
    }
    
    Jumping on the IT blogging band wagon -- http://www.jefferyland.com/
  • Options
    DevilWAHDevilWAH Member Posts: 2,997 ■■■■■■■■□□
    you might need to play with this as it is pulled out from VBA script,

    but the basic idea is that the function accepts an array of strings each of which may or maynot contain a varible. this are always in the form of *** xxxx *** (the tag has to be 4 charaturs in lenth. this simple means a litle less code to manage), but this is easly update to accomidate new code

    along with a dictonary object that contains the value asoicated with each varible.

    the function will return a arry containg the strings from the origianl array, with the varibles replaced.

    I use it by creating a loop and upadating the varbiels from a spread sheet and returning the code to implement

    if you want the code as a single string you can simple parse the returned array though the following loop at the end

    see atached PDF for screen shot of the sheet I use thsi code in to give you an idea of its purpose.
    sub populate()
     
    Dim mIOSconfig
    Dim mCATconfig
    DIM nconfigcatos
    DIM nconfigios
     
    mIOSconfig = Array("  ! *** SRMS ***  ", "int *** PORT ***", "switchport access vlan *** VLAN ***", "description *** DESC ***", "speed *** SPEE ***", "duplex *** DUPL ***", "  *** SHUT ***  ", "Exit")
    mCATconfig = Array("  ! *** SRMS ***  ", "set port name *** DESC *** *** PORT ***   ", "set vlan *** VLAN *** *** PORT ***   ", "set port *** SHUT *** *** PORT ***   ", "YES")
     
    Set Newconfig = CreateObject("Scripting.Dictionary")  ' populate from Spread sheet or other extrnal source using a loop
        Newconfig.Item("*** PORT ***") = "G1/5"
        Newconfig.Item("*** VLAN ***") = "56"
        Newconfig.Item("*** SPEE ***") = "100"
        Newconfig.Item("*** DUPL ***") = "full"
        Newconfig.Item("*** DESC ***") = "my_server"
        Newconfig.Item("*** SHUT ***") = "no shut"
        Newconfig.Item("*** SRMS ***") = "ref12345"
     
    nconfigcatos = writetconf(mCATconfig, Newconfig)
    nconfigios = writetconf(mCATconfig, Newconfig)
     
    end sub
     
     
    Function writetconf(master, vals) ' master config array, valuse to be replaced
    num = UBound(master)
    ReDim temps(num) ' will be used to hold config before it is passed back
    For x = 0 To num   ' loop to step through elements in master config array
    temps(x) = master(x)
    Do While InStr(1, temps(x), "***") <> 0  ' check if element has more than one varible with in it
    first = InStr(temps(x), "***")   ' find start postition of varible
    snip = Mid(temps(x), first, 12)  ' pull out varible from master config and then replace using dictonary items
     
    temps(x) = Replace(temps(x), snip, vals.Item(snip))
    Loop
    temps(x) = Trim(temps(x))
    Next
    writetconf = temps  ' copy to varible to pass back
    End Function
    
     
    nconf = "" ' empty the varible
    For i = 0 To UBound(nconfig) 'convert the config array data to a text string
        nconf = nconf & nconfigios(i) & vbCrLf
        Next
    

    this would give you something like

    ! ref12345
    int g1/5
    swith port access vlan 56
    speed 100
    duplex full
    description my_server
    no shut
    • If you can't explain it simply, you don't understand it well enough. Albert Einstein
    • An arrow can only be shot by pulling it backward. So when life is dragging you back with difficulties. It means that its going to launch you into something great. So just focus and keep aiming.
  • Options
    undomielundomiel Member Posts: 2,818
    Time to resurrect this thread. Back with a couple more scripts. These require PowerShell v2. GetServices.ps1 will scan a given list of systems and return all of the services configured with a service account and that count name. It will also out a CSV for each host as well. SetServices.ps1 will then take the same CSVs, once you add a Password column, and update all of the specified service accounts on the server with the password in the CSV. Hope this will help someone, it certainly will be saving me a lot of tedium in up coming weeks.

    GetServices.ps1
    # Script for scanning a server for all services running under
    # service accounts. It will import the list of servers from a file
    # and scan those servers for any service accounts, it will then
    # **** that server to its own csv listing the services and accounts
    # which you can then later manipulate for your purposes
    
    # Display help and exit
    if (($args[0] -eq "-?") -or ($args[0] -eq "-help") -or ($args.count -eq 0))
    {
      ""
      "Usage: GetService.ps1"
      "  Get services using service accounts from machines specified in a plain text file"
      ""
      "Example: "
      "GetService.ps1 hostlist.txt"
      exit
    }
    
    # Pass a service name in and check to see if it matches the excluded
    # service accounts that you've preconfigured
    function CheckServiceName($ThisServiceName)
    {
      foreach($ExcludedName in $ExcludedServices)
      {
         if($ThisServiceName -eq $ExcludedName.ToLower())
         {
           return $true
         }
      }
      return $false
    }
    
    # Default system accounts to exclude
    $ExcludedServices = "NT AUTHORITY\LocalService", "LocalSystem", "NT AUTHORITY\NETWORK SERVICE", "NT AUTHORITY\NetworkService"
    
    # Will pop up a prompt to provide credentials for making WMI calls
    # to the remote systems
    $Credentials = Get-Credential
    
    # Reads in the list of systems to scan from the first
    # argument passed to the script
    $HostList = Get-Content $args[0]
    $CSVCount = 0
    $HostName = Get-Content env:computername
    
    # Our main loop, iterates through each system listed in
    # the file and pulls all of their services
    foreach($HostServer in $HostList)
    {
      if ($HostServer -ne $HostName)
      {
        $ServiceList = get-WMIObject win32_service -computername $HostServer -credential $Credentials -property name,startname
      }
      else
      {
        $ServiceList = get-WMIObject win32_service -computername $HostServer -property name,startname
      }
    
      [array]$CSVArray = $null
    
      foreach($ThisService in $ServiceList)
      {
        $CheckResult = CheckServiceName($ThisService.StartName.ToLower())
        if ($CheckResult -eq $false)
        {
          Write-Host "Service: " $ThisService.name
          Write-Host "Account: " $ThisService.StartName
          $CSVArray += ,$ThisService | select Name,StartName    
        }
      }
    
      if ($CSVArray.count -gt 0)
      {
        Write-Host "Saving .csv for $HostServer"
        Write-Host ""
        $CSVArray | Export-CSV "$HostServer.csv"
        $CSVCount++
      }
    }
    
    if ($CSVCount -gt 1)
    {
      Write-Host "Done, wrote out $CSVCount .csv files."
    }
    elseif ($CSVCount -eq 1)
    {
      Write-Host "Done, wrote out $CSVCount .csv file."
    }
    elseif ($CSVCount -eq 0)
    {
      Write-Host "No .csv files written out, no service accounts found."
    }
    

    SetServices.ps1
    # Change the service account and password on a service
    # on the specified system
    
    # Display help and exit
    if (($args[0] -eq "-?") -or ($args[0] -eq "-help") -or ($args.count -eq 0))
    {
      ""
      "Usage: SetServices.ps1"
      "  Set services using service accounts for the server specified in a plain text CSV file"
      ""
      "Example: "
      "SetServices.ps1 host.csv"
      exit
    }
    
    
    # Will pop up a prompt to provide credentials for making WMI calls
    # to the remote systems
    $Credentials = Get-Credential
    
    $HostName = Get-Content env:computername
    
    # Read in the CSV and also parse out the host name
    # from the CSV name
    $ServerCSV = Import-CSV $args[0]
    $ServerName = $args[0].Substring(0,($args[0].length - 4))
    
    # Main loop, reads in each service then sets the
    # account name and password on the service
    # then it stops and starts the service to verify
    # that everything is working as planned
    foreach($ThisService in $ServerCSV)
    {
      # Checking to see if you're missing the password column or have a blank
      # password, if it didn't check then you could hose a lot of services
      if ($ThisService.Password -eq $null)
      {
        Write-Host "Verify your password column."
        exit
      }
      
      # Grab the service from the system
      if ($ServerName -ne $HostName)
      {
        $TargetService = Get-WMIObject win32_service -computername $ServerName -credential $Credentials -filter "name='$($ThisService.Name)'"
      }
      else
      {
        $TargetService = Get-WMIObject win32_service -computername $ServerName -filter "name='$($ThisService.Name)'"
      }
    
      # Update the service and test the return code
      $result = $TargetService.Change($null,$null,$null,$null,$null,$null,$ThisService.StartName,$ThisService.Password,$null,$null,$null)
      if ($result.ReturnValue -eq 0)
      {
        Write-Host "$($ThisService.Name) has been updated successfully."
      }
      else
      {
        Write-Host "Failed to update $($ThisService.StartName)."
      }
    
      # If successful then we'll restart the services
      if($result.ReturnValue -eq 0)
      {
        $result = $TargetService.StopService()
        if ($result.ReturnValue -eq 0)
        {
           Write-Host "$($ThisService.Name) successfully stopped."
        }
        elseif ($result.ReturnValue -eq 5)
        {
           Write-Host "$($ThisService.Name) has already been stopped."
        }
        else
        {
           Write-Host "An unknown error occurred stopping $ThisService.StartName."
        }
        $result = $TargetService.StartService()
        if ($result.ReturnValue -eq 0)
        {
          Write-Host "$($ThisService.Name) has been successfully started."
        }
        elseif ($result.ReturnValue -eq [IMG]https://us.v-cdn.net/6030959/uploads/images/smilies/icon_cool.gif[/IMG]
        {
          Write-Host "$($ThisService.Name) cannot be started in this account's context."
        }
        elseif ($result.ReturnValue -eq 14)
        {
          Write-Host "$($ThisService.Name) is disabled and cannot start."
        }
        elseif ($result.ReturnValue -eq 15)
        {
          Write-Host "$($ThisService.Name) cannot be started as the credentials are invalid."
          Write-Host "Please check the username and password and try again."
        }
      }
    }
    
    
    Jumping on the IT blogging band wagon -- http://www.jefferyland.com/
  • Options
    DevilWAHDevilWAH Member Posts: 2,997 ■■■■■■■■□□
    So last time i was here i had a script for creating config for Cisco devices, or more strictly port provisioning for updating vlan and port description.

    That was a bit specific and not very flexible so I decided to lean c# and make a more generic tool.

    This one takes the master config from a simple txt config file, creates the GUI form for the use to enter the varibles and outputs the final script.

    See screen shot below.



    if people want to have a look here is a zip file with the stand alone app + example cofig file, but as long as you follow the lay out any config will work no matter the size.

    Be aware it is not complete and needs a fair bit of tidying up, want to out put to a templated word doc / text / download. and also introduce a menu driven system so you don't have to File >> open each time you want to change config.

    But for now if any one wants to have a look, or has suggestiong to make it more usefull let me know

    confgen

    PS you will need .net framework 3.5 installed, to run this.

    If you are deploying generic configs to mutiple devices with only minor changes you may find this a helpfull tool.

    If nothing else it has been a nice project to get my head around c#

    DevilWAH
    • If you can't explain it simply, you don't understand it well enough. Albert Einstein
    • An arrow can only be shot by pulling it backward. So when life is dragging you back with difficulties. It means that its going to launch you into something great. So just focus and keep aiming.
  • Options
    whatthehellwhatthehell Member Posts: 920
    undomiel wrote: »
    Time to resurrect this thread. Back with a couple more scripts. These require PowerShell v2. GetServices.ps1 will scan a given list of systems and return all of the services configured with a service account and that count name. It will also out a CSV for each host as well. SetServices.ps1 will then take the same CSVs, once you add a Password column, and update all of the specified service accounts on the server with the password in the CSV. Hope this will help someone, it certainly will be saving me a lot of tedium in up coming weeks.

    GetServices.ps1
    # Script for scanning a server for all services running under
    # service accounts. It will import the list of servers from a file
    # and scan those servers for any service accounts, it will then
    # **** that server to its own csv listing the services and accounts
    # which you can then later manipulate for your purposes
    
    # Display help and exit
    if (($args[0] -eq "-?") -or ($args[0] -eq "-help") -or ($args.count -eq 0))
    {
      ""
      "Usage: GetService.ps1"
      "  Get services using service accounts from machines specified in a plain text file"
      ""
      "Example: "
      "GetService.ps1 hostlist.txt"
      exit
    }
    
    # Pass a service name in and check to see if it matches the excluded
    # service accounts that you've preconfigured
    function CheckServiceName($ThisServiceName)
    {
      foreach($ExcludedName in $ExcludedServices)
      {
         if($ThisServiceName -eq $ExcludedName.ToLower())
         {
           return $true
         }
      }
      return $false
    }
    
    # Default system accounts to exclude
    $ExcludedServices = "NT AUTHORITY\LocalService", "LocalSystem", "NT AUTHORITY\NETWORK SERVICE", "NT AUTHORITY\NetworkService"
    
    # Will pop up a prompt to provide credentials for making WMI calls
    # to the remote systems
    $Credentials = Get-Credential
    
    # Reads in the list of systems to scan from the first
    # argument passed to the script
    $HostList = Get-Content $args[0]
    $CSVCount = 0
    $HostName = Get-Content env:computername
    
    # Our main loop, iterates through each system listed in
    # the file and pulls all of their services
    foreach($HostServer in $HostList)
    {
      if ($HostServer -ne $HostName)
      {
        $ServiceList = get-WMIObject win32_service -computername $HostServer -credential $Credentials -property name,startname
      }
      else
      {
        $ServiceList = get-WMIObject win32_service -computername $HostServer -property name,startname
      }
    
      [array]$CSVArray = $null
    
      foreach($ThisService in $ServiceList)
      {
        $CheckResult = CheckServiceName($ThisService.StartName.ToLower())
        if ($CheckResult -eq $false)
        {
          Write-Host "Service: " $ThisService.name
          Write-Host "Account: " $ThisService.StartName
          $CSVArray += ,$ThisService | select Name,StartName    
        }
      }
    
      if ($CSVArray.count -gt 0)
      {
        Write-Host "Saving .csv for $HostServer"
        Write-Host ""
        $CSVArray | Export-CSV "$HostServer.csv"
        $CSVCount++
      }
    }
    
    if ($CSVCount -gt 1)
    {
      Write-Host "Done, wrote out $CSVCount .csv files."
    }
    elseif ($CSVCount -eq 1)
    {
      Write-Host "Done, wrote out $CSVCount .csv file."
    }
    elseif ($CSVCount -eq 0)
    {
      Write-Host "No .csv files written out, no service accounts found."
    }
    

    SetServices.ps1
    # Change the service account and password on a service
    # on the specified system
    
    # Display help and exit
    if (($args[0] -eq "-?") -or ($args[0] -eq "-help") -or ($args.count -eq 0))
    {
      ""
      "Usage: SetServices.ps1"
      "  Set services using service accounts for the server specified in a plain text CSV file"
      ""
      "Example: "
      "SetServices.ps1 host.csv"
      exit
    }
    
    
    # Will pop up a prompt to provide credentials for making WMI calls
    # to the remote systems
    $Credentials = Get-Credential
    
    $HostName = Get-Content env:computername
    
    # Read in the CSV and also parse out the host name
    # from the CSV name
    $ServerCSV = Import-CSV $args[0]
    $ServerName = $args[0].Substring(0,($args[0].length - 4))
    
    # Main loop, reads in each service then sets the
    # account name and password on the service
    # then it stops and starts the service to verify
    # that everything is working as planned
    foreach($ThisService in $ServerCSV)
    {
      # Checking to see if you're missing the password column or have a blank
      # password, if it didn't check then you could hose a lot of services
      if ($ThisService.Password -eq $null)
      {
        Write-Host "Verify your password column."
        exit
      }
      
      # Grab the service from the system
      if ($ServerName -ne $HostName)
      {
        $TargetService = Get-WMIObject win32_service -computername $ServerName -credential $Credentials -filter "name='$($ThisService.Name)'"
      }
      else
      {
        $TargetService = Get-WMIObject win32_service -computername $ServerName -filter "name='$($ThisService.Name)'"
      }
    
      # Update the service and test the return code
      $result = $TargetService.Change($null,$null,$null,$null,$null,$null,$ThisService.StartName,$ThisService.Password,$null,$null,$null)
      if ($result.ReturnValue -eq 0)
      {
        Write-Host "$($ThisService.Name) has been updated successfully."
      }
      else
      {
        Write-Host "Failed to update $($ThisService.StartName)."
      }
    
      # If successful then we'll restart the services
      if($result.ReturnValue -eq 0)
      {
        $result = $TargetService.StopService()
        if ($result.ReturnValue -eq 0)
        {
           Write-Host "$($ThisService.Name) successfully stopped."
        }
        elseif ($result.ReturnValue -eq 5)
        {
           Write-Host "$($ThisService.Name) has already been stopped."
        }
        else
        {
           Write-Host "An unknown error occurred stopping $ThisService.StartName."
        }
        $result = $TargetService.StartService()
        if ($result.ReturnValue -eq 0)
        {
          Write-Host "$($ThisService.Name) has been successfully started."
        }
        elseif ($result.ReturnValue -eq [IMG]https://us.v-cdn.net/6030959/uploads/images/smilies/icon_cool.gif[/IMG]
        {
          Write-Host "$($ThisService.Name) cannot be started in this account's context."
        }
        elseif ($result.ReturnValue -eq 14)
        {
          Write-Host "$($ThisService.Name) is disabled and cannot start."
        }
        elseif ($result.ReturnValue -eq 15)
        {
          Write-Host "$($ThisService.Name) cannot be started as the credentials are invalid."
          Write-Host "Please check the username and password and try again."
        }
      }
    }
    
    

    +1 for you! This is awesome, and exactly what I needed to troubleshoot some nastier issues at work.

    Much appreciated! :)
    2017 Goals:
    [ ] Security + [ ] 74-409 [ ] CEH
    Future Goals:
    TBD
  • Options
    DevilWAHDevilWAH Member Posts: 2,997 ■■■■■■■■□□
    Here is a little tip for scripting with SecureCRT.

    The scripting function in SecureCRT is great for basic tasks, and for those of you that used is you will know the command
    crt.screen.WaitForStrings ">", "#" 
    
    which makes the script wait on a cisco device until the prompt is back. But this has an problem, if for any reason the return string has one of these ">" or "#" then the script will continue. For example if some one has used ###servername### as part of a interface description, the script will continue to run before the output has completed.

    Easy way to get around this is.
    Do While CRT.Screen.WaitForCursor(1)
    crt.screen.WaitForStrings ">", "#"
    Loop
    

    the Wait for cursor loop will keep looping untill the cursor is stationary for 1 second, and the prompt has been returned.

    There are other ways to achive the same, but I find they slow down the script. Placing the waitforstrings inside the loop keeps things moving, and only invokes the waitforcursor check (which is what slows things down) for lines that contain the prompt string.

    There is also a good bit in the documatation about creating custom user dialogs for secureCRT scripts using HTML forms and button controls. Been putting new GUI's to all my scripts latley.


    DevilWAH
    • If you can't explain it simply, you don't understand it well enough. Albert Einstein
    • An arrow can only be shot by pulling it backward. So when life is dragging you back with difficulties. It means that its going to launch you into something great. So just focus and keep aiming.
  • Options
    whatthehellwhatthehell Member Posts: 920
    Anyone recommend any good sites, books, ebooks, tutorials, etc for PowerShell?
    2017 Goals:
    [ ] Security + [ ] 74-409 [ ] CEH
    Future Goals:
    TBD
  • Options
    RobertKaucherRobertKaucher Member Posts: 4,299 ■■■■■■■■■■
    PowerShell in a Month of Lunches and PowerShell in Action are both really good. You can also look at the administration books (Automating Windows Server 2008 Administration with Windows PowerShell and Automating MS SharePoint 2010 Administration with Windows PowerShell, etc).
  • Options
    whatthehellwhatthehell Member Posts: 920
    PowerShell in a Month of Lunches and PowerShell in Action are both really good. You can also look at the administration books (Automating Windows Server 2008 Administration with Windows PowerShell and Automating MS SharePoint 2010 Administration with Windows PowerShell, etc).

    *bow* thanks very much sir! :)
    2017 Goals:
    [ ] Security + [ ] 74-409 [ ] CEH
    Future Goals:
    TBD
Sign In or Register to comment.