DRIVE EFFICIENCY THROUGH AUTOMATED IT.
SAVE COST THROUGH CONSOLIDATION OF IT.
WANT TO KNOW MORE ABOUT STRATEGIC CONSULTING CLICK HERE.
MICROSOFT / RISUAL HYPER-V CLOUD EVENT 22ND MARCH 2011 CLICKHERE.

Archive

Posts Tagged ‘Powershell’

Run PowerShell Script Remotely

June 2nd, 2011 Daniel Davies Comments off

If you have PowerShell 2.0 installed on machines in your environment, then you are able to execute PowerShell scripts on remote machines straight from your local machine.

First make sure you enable remote script execution on your Local and Remote machine by running the following in PowerShell.

Enable-PSRemoting –force

Now place the PowerShell script you want to execute on a location on your local machine.

Now we can run the following PowerShell command to execute the script on the remote machine Smile (Edit the below highlighted in red to match the remote machine name and the PowerShell file location)

Invoke-Command -ComputerName machinename -FilePath C:FileLocationfilename.ps1

Categories: Uncategorized Tags: ,

Exchange PowerShell command to show permissions on a particular or all users mailboxes

April 28th, 2011 Daniel Davies Comments off

We had a request recently to list what users have rights to a specific users mailbox.

This can easily be done using the following command.

Get-MailboxPermission –Identity “UserName” | fl user, accessrights

This gives an output like below.

image

If you would like to see permissions for every users mailbox run the following command

Get-MailboxPermission -Identity * | fl user, accessrights , identity > C:Perms.txt
(You can change the file location to wherever you would like)

The list of the Users and Permissions will all be in the Perms.txt file.

Do not prompt when writing to output file in DPM PowerShell

April 14th, 2011 paulw Comments off

Just a quick one for anyone else that uses a DPM PowerShell command to output to a file and keeps getting prompted to perform the action:

image

If you are writing anything that has a for each clause in there then you can end up typing “Y” for each time it wants to write to the file.

All you need to do is add in the following option at the end of your line:

-confirm:$false

So the example command from above would read:

“What you want to output” | out-file “c:outputfile.txt” -confirm:$false

The file should then overwrite without prompting.

Paul

Categories: Uncategorized Tags: ,

Service Manager PowerShell Script to close resolved cased after 2 days of inactivity

March 11th, 2011 Daniel Davies Comments off

Just a quick PowerShell script which will close any case that have been Inactive for 2 days and are currently in a resolved state in Service Manager.

CMDLets from “http://smlets.codeplex.com/

Import-Module SMLets
Get-SCSMIncident -Status resolved -InactiveFor 2.00:00:00 | Set-SCSMIncident -Status Closed -Comment “Comment Here” 

Delete IIS logs after certain number of days via PowerShell

February 17th, 2011 Daniel Davies Comments off

Just a quick script that may come in useful to you. The below Powershell script will delete IIS Log files older than 7 days that are in the “C:inetpublogsLogFilesw3svc1” directory. You can alter the script to how many days old the log files can be and also your IIS log location (Highlighted in red).

get-childitem -Path C:inetpublogsLogFilesw3svc1 -recurse | where-object {$_.lastwritetime -lt (get-date).addDays(-7)} | Foreach-Object { del $_.FullName }

Categories: Uncategorized Tags: ,

PowerShell string manipulation

August 18th, 2010 Joe Comments off

Whilst trying to automate some reporting automation and analysis , I overcome a requirement to reformat a csv ( loosest sense of the term) so that PowerShell will process it.  The following is a useful demonstration of how to manipulate text data and reformat it, also the use of regex (Regular Expression) in PowerShell to identify the current days file.

This has been tested against PowerShell 1.0 on Microsoft Windows Server 2003

##
# A csv Files report is created but you are unable to load it as a csv File due to irregular  formatting of the report.
# this will serve as a good example of string manipulation.
#
# Issues with csv file
# remove top 6 lines, header information not required.
# headers contain , but are not quoted, so you now have more columns than data
# trailing , stop PowerShell loading csv as you can not have a blank header
# the data is includes a % sign.  this then stop it being a number when imported into SQL / Excel
#———————————————————–
#
#
$tmpfile    = “temp.csv”
$mydat        = (get-date ((get-date).adddays(-1))-uformat “%Y%m%d”)    # get yesterdays date in the correct format
$filter        = [regex] “^Daily-View.*$mydat[0-9]{6}.csv$”            # Use regex to find today’s file
$csvfile    = Get-ChildItem -Path “c:Joetest*.csv” | Where-Object {$_.Name -match $filter} # return 1 filename

#              use PowerShell to drop the first 6 lines of unwanted text at the beginning of the file
#

$csvContent = get-content $csvfile

$csvContent | select -last ($csvContent.count -6) | Out-File $tmpfile

#             replace “, %”   with  ” %” 
#
$csvContent = “”
$csvContent = get-content $tmpfile
$csvContent[0] = $csvContent[0].replace(“, %”,” %”)

#             remove trailing , on header line
#
$csvContent[0] = $csvContent[0].substring(0,($csvContent[0].length)-1)     # remove the last char on the line

#             remove all the “%” signs from the data  ( but not the header) 
#

$counter = 0
foreach ($line in $csvContent)
{
    if ($counter -ne 0)     # skip the header line
    {
    $csvContent[$counter] =$csvContent[$counter].replace(“%”,”")
    }
$counter++
}

#            output the plain txt file
#
$csvContent | out-file $tmpfile

#             now you can import the file as a csv with no errors
#
$csvdata = import-csv $tmpfile
$csvdata

#        ————————————–
#         now you can do stuff with the data here
#        ————————————–

#         Remove old temp file
#
if (test-path $tmpfile)
    {
        remove-item -path $tmpfile -force
    }

Categories: Uncategorized Tags: ,

Archiving Event Logs

June 3rd, 2010 Rob Comments off

As part of a recent engagement I was asked to implement a solution to automatically export & archive System and Security logs from servers to a central location, the requirements were:

  • Nightly time stamped archive of Security and System event logs to a central location
  • Clear the local log once the archive has been successfully taken

I put together the following PowerShell script to achieve the above:

 

$locallocation = "c:logs"
$remotelocation = "\fileserverEventLogs"
$localmachine = $env:computername

$evtlgs = Get-WMIObject -Class Win32_NTEventLogFile -Computer $localmachine
foreach ($log in $evtlgs)
    {
    if ($log.LogFileName -eq "System" -or $log.LogFileName -eq "Security")
        {
        $timestamp = get-date -f yyyyMMddHHmmss
        $path = $log.LogFileName + $timestamp
        $store = $locallocation+$path+".evt"
        $backup = ($log.backupeventlog($store)).ReturnValue
        if($backup -eq 0)
            {
            $log.ClearEventLog() | out-null
            }     
        move-item $locallocation* $remotelocation$localmachine
        }
    }

The above script is executed by a Scheduled Task (which on another note are brilliant on Server 2008), the lines you’re interested in are the top 2 lines which configure a local location to write the log out to and the remote location to move the log to once it has been written.  I ran this script using a service account which has permission to write to the local and remote locations. 

If you wanted a different selection of logs to be archived you would adjust the

if ($log.LogFileName -eq "System" -or $log.LogFileName -eq "Security")

line to suit your requirements.

In our requirement the logs had to be archived daily, this was simply achieved by configuring task scheduler to run once per day at the desired time, no code changes are required. 

The requirement for only clearing the local log if the export was successful is met by checking the exit code form the backup, if this wasn’t 0 then the log wont be cleared.

Categories: Uncategorized Tags: ,

Bulk Mailbox Moves Exchange 2010

February 2nd, 2010 Daniel Davies Comments off

You may come across an issue where you need to Migrate Multiple Mailboxes in bulk, we’ve created a Exchange Powershell script which will move all users into there targeted mail stores.

Instructions

Before we run this powershell script  we need to create a csv file with the users display name and there targeted exchange database, to do this see below.

1, open notepad.exe

2, now write the following text on your first line in notepad “user,database” (without quotation marks)

3, Go to the next line and then type a users name  first and then add a comma and finally type the desired store.

4, You should end up with a list like below with all the users you want to import

user,Database
Jovan Davis,Store 3
Daniel Davies,Store 2
Hardeep Bains,Store 1

5, Finally save the file as a csv file and name it “MM.csv” in the following directory “C:MailboxMove””

6, Now open notepad again and copy all the below text into it. Finally save this as a PS1 file and run this via the Exchange management Shell.
_________________________________________________________________________

$Userstodatabase = import-csv C:MailboxMoveMM.csv
foreach ($Record in $Userstodatabase)
{
$users = $record.user
$database = $record.database
New-MoveRequest –identity $users –TargetDatabase “$Database”
}

____________________________________________________________________________

This will now move the mailboxes :)

If you want to check the status if the moves simply copy the below script into a PS1 file and run it from the exchange shell and it will list the progress of all users mailboxes specified in the CSV.

____________________________________________________________________________

$Userstodatabase = import-csv C:MailboxMoveMM.csv
foreach ($Record in $Userstodatabase)
{
$users = $record.user
Get-MoveRequest –identity $users
}

___________________________________________________________________________ 

Hope this helps :)

Daniel Davies