Showing posts with label Scripts. Show all posts
Showing posts with label Scripts. Show all posts

Monday, June 04, 2018

Export IIS bindings

I find the cmdlet for exporting cmdlets a bit lacking so I built my own export function for fun and profit.
The function in the toolsfile collects all info and return a populated object that can be used to export list to file or do something else with.

Tuesday, January 26, 2016

A fun script for creating meetings in Outlook.
For the very lazy admin

function createMeeting(
    $Subject = "Test Meeting",
    $body = "Just Testing",
    $location = "Here",
    $start = "1/26/2016 12:00 PM",
    $duration = 60,
    $reminderSet = $true,
    $reminderMinutesBeforeStart = 15
    )
{
$olAppointmentItem = 1
$o = New-Object -comobject outlook.application
$a = $o.CreateItem($olAppointmentItem)
$a.MeetingStatus.olMeeting
$a.Start = $start
$a.Duration = $duration
$a.Subject = $Subject
$a.body = $body
$a.Location = $location
$a.ReminderMinutesBeforeStart = $reminderMinutesBeforeStart
$a.reminderSet = $true
$result = $a.Save()
}


$Duration = 60
$Subject = "Test1"
$Body = "testar2"
$Location="Office"
$ReminderMinutesBeforeStart = 30
$reminderSet = $true

#This scenario is set of dates with same meeting time
$arrayOfDates =  "2016-01-26", "2016-01-27","2016-01-28"
$hour = 10
$minute = 00
for ($i=0;$i -le ($ArrayOfDates.count-1);$i++) {
$dateTime = get-date $ArrayOfDates[$i] -Hour $hour -Minute $minute
$dateTime
createMeeting -Subject $Subject -body $Body -location $Location -reminderSet $reminderSet -reminderMinutesBeforeStart $ReminderMinutesBeforeStart -duration $Duration -start $dateTime
}

References:
https://social.technet.microsoft.com/Forums/windowsserver/en-US/077733c5-6e39-489e-908a-d3098c512a71/need-to-create-meeting-request-using-powershell-with-outlook-2010-2013?forum=winserverpowershell

Tuesday, September 29, 2015

Speedier scripts

Some notes on how to handle output from scripts.
I did some comparing on how much extra time is added on executiontime just by using write-output to display information to users.
While running script below these are the results:

With write-output uncommented : 11,8s
With write-progress uncommented: 3,9s
With no output: 0,9s

$global:varNumb = 1

function foo {

 #write-host "entering function 'foo'"

 write-verbose "entering function 'foo'"

 $global:varNumb++

 #write-host "completed function 'foo' $varnumb"

 write-verbose "completed function 'foo' $global:varnumb"

}

 

$startTime = get-date

write-host "script started at $startime"

$cycles = 1000

$i = 1

1..$cycles | foreach {

 #write-progress -Activity "Processing..." -CurrentOperation "Working on $i"

 #write-output "Testar $i"

 $i++

foo

}

 

$endtime = get-date

write-host "Done in $(($endtime-$starttime).totalseconds) seconds"

 

$global:varNumb

 

Its amazing how much time is added just by adding write-output.
But as seen in this example write-progress is prefererred, if anything.
I suggest using write-verbose instead of write-output and changing $verbosepreference = Continue when needed. This is by default SilentlyContinue

 

References:
http://blogs.technet.com/b/kpalmvig/archive/2013/10/29/easy-progress-bar-in-your-powershell-scripts.aspx

Monday, July 06, 2015

csv-loop snippet

 

This example reads from mycsv.csv in same folder as script is.
-----------------csv-loop.ps1------------------
#settings#
$myfilename = "mycsv.csv"

#settings end
$importfile = "$(split-path -Parent $myinvocation.MyCommand.Definition)\$myfilename"
import-csv $importfile -Delimiter "," |foreach-object {
#All things here will execute towards every line of $myfilename
write-host "$($_.fullpath) , $($_.site) , $($_.file)"
}
------------------eof-----------------------------

----------------mycsv.csv--------------------
fullpath,site,file
test1,test2,test3
test4,test5,test6
-------------------eof---------------------------

Monday, March 09, 2015

Upload files to library

Simple script to upload all files from specific folder to documentlibrary.

 

$path = "C:\myfiles\TestDocs";

$user = "mydomain\john.doe"

$pass= "mysecretpassword"

$destination = "https://mysite.mycompany.com/mylib";

 

 

$securePasssword = ConvertTo-SecureString $pass -AsPlainText -Force;

$credentials = New-Object System.Management.Automation.PSCredential ($user, $securePasssword);

#$credentials = [System.Net.CredentialCache]::DefaultCredentials;

 

$webclient = New-Object System.Net.WebClient;

$webclient.Credentials = $credentials;

 

Get-ChildItem $path | Where-Object {$_.Length -gt 0} | ForEach-Object { $webclient.UploadFile($destination + "/" + $_.Name, "PUT", $_.FullName)};

 

Thursday, February 26, 2015

Retrieve latest timerjobs


To get a quick overview over latest timerruns and get rid of scrolling endlessly in Central Admin
-----getTimerJobHistories.ps1--------
Add-PSSnapin microsoft.sharepoint.powershell
$number= 10 #total results
$timername = "User Profile Service Application_LMTRepopulationJob"
$timerjob = Get-SPTimerJob $timername
$timerjob.HistoryEntries | select jobdefinitiontitle,starttime,endtime,status,errormessage -first $number|format-table
#$timerjob.HistoryEntries
------------eof---------------------

Sunday, November 23, 2014

Powershell and firewalls

Finally with Windows 8.1 and Server 2012 we have some new cmdlets that make managing firewall-rules much easier. Hopefully we can now put netsh to the everlasting rest.

Example script – blockapps.ps1

$rulename = "BlockSomething"
$appPath = "D:\temp\Myprogram.exe"
New-NetFirewallRule -displayname $rulename -Direction Outbound -Program $appPath -action Block

 

References:

http://technet.microsoft.com/en-us/library/jj554908.aspx – cmd syntax

Tuesday, October 07, 2014

Powershell and xml

For future reference
script to read properties from a xml file and update specified values.
More of a proof of concept than any real world usage.
Good for any cocktailparty
----------------xmllooptest.ps1 ---------
$path = split-path -parent $MyInvocation.MyCommand.Definition
$inputfile = $path + "\myinputfile3.xml"
[xml]$xmlinput = (Get-Content $inputFile)

write-host $xmlinput.main.configuration.name" is my value"
write-host "Server is:"$xmlinput.main.configuration.server
write-host "Result : "$xmlinput.main.configuration.result


Write-host "Looping sites..."
$sites = $xmlinput.main.sites.site
foreach ($site in $sites)
{
    write-host "-----"
    write-host $site.name
    write-host $site.property
    if ($site.name -match "my site 2")
    {
    $site.property = "New property for site2"
    }
    write-host $site.property
   
}
$xmlinput.save($inputfile)
-----------------------eof-----------------
----------------- myInputfile3.xml------------


 
    myserver
    Wyoming
    Testing
 

 
   
      my site 1
      My even newer property
   

   
      my site 2
      New property for site2
   

 
--------------------eof--------------

Wednesday, February 05, 2014

Schedule a powershell script

When certain task has run, its nice to be notified. since email function is deprecated in taskscheduler we have to pull out powershell.

image

1. Create the script

-------sendmail.ps1-----

param([string]$task)
$psemailserver = "smtp.mycompany.com"
$receiver = john.doe@company.com
$from = task@company.com
$subject = "Task has run"
$body = "Scheduled task $task has run. "
send-mailmessage -to $receiver -from $from -subject $subject -body $body
write-host "Mail sent for $task"
write-eventlog -logname Application -source "my script" -entrytype information -eventid 1 -message "$task has run"
------eof----

2. Create the call using Task Scheduler “powershell –file “c:\myfile\sendmail.ps1” “helloworld”

What the script does is take an input variable and sending an email using defined smtpserver in the script. When mail is sent, it also logs en event in the application eventlog with source “my script”. The param is optional, but helpful if you want more reusability.

The source needs to created the first time manually, or use an already existing source.

Create source “my script” in application

/>New-eventlog –logname application –source ”my script”

References:

http://blogs.technet.com/b/heyscriptingguy/archive/2013/06/20/how-to-use-powershell-to-write-to-event-logs.aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx

http://stackoverflow.com/questions/16426688/passing-a-variable-to-a-powershell-script-via-command-line

Thursday, September 26, 2013

Set calender permissions for all users

To check permissions for calender on a user:

/> get-mailboxfolderpermission john.doe:\calender

To Set permissions for user default to reviewer on john.does calender

/>set-mailboxfolderpermission john.doe:\calendar –user Default –Accessrights Reviewer

To script this for all users

--------------SetCalendarReviewer.ps1-------------

foreach ($user in get-content users.txt)

{

set-mailboxfolderpermission ${user}:\calendar -user Default -Accessrights Reviewer

write-host "$user is processed."

}

----------------------------eof----------------------------------

It retrievs all users from test.txt which is simply one username per line.

Also below is a link to policy to always set this permission with newly created users, which I haven’t tried out yet.

References:

http://stackoverflow.com/questions/15612088/how-to-combine-variable-with-the-rest-of-the-command

http://exchangeinside.org/2013/01/set-default-calendar-permissions-for-all-new-users-to-reviewer/

http://technet.microsoft.com/en-us/library/dd351181%28v=exchg.150%29.aspx – remove-mailboxfolderpermission

http://technet.microsoft.com/en-us/library/ff522363%28v=exchg.150%29.aspx – set-mailboxfolderpermissions

Wednesday, September 11, 2013

Check last logon time in E2013

Ok, so gui pretty much out in Exchange 2013.
So if I want to check when users last logged on the mailbox for some reason we use powershell.
Make a script, typing is going to get old real fast.
To check latest logintime for users
-----------CheckLastlogon.ps1-------------
add-pssnapin microsoft.exchange.management.powershell.snapin
foreach ($user in get-content users.txt)
{
get-mailboxstatistics $user |select displayname,itemcount,lastlogontime,totalitemsize
}
---------------eof----------------------------------





If you want the results in a pretty displaybox, you can pipe |out-gridview like .\checklastlogon.ps1 | out-gridview.
To make the script pause after printing, add these lines:

write-host "press any key to end"
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Good for those diehard powerhaters out there, or in here…
References:
http://exchangeserverpro.com/last-logon-time-exchange-2010-mailbox-users/



Powershell and Uptimerobot

Uptimerobot can be quite tedious when you need to update many monitors at once. For example say you bought the license for Uptimerobot and n...