Showing posts with label one-liner. Show all posts
Showing posts with label one-liner. Show all posts

Thursday, September 6, 2007

Playing sounds in PowerShell

 

You can play sounds in PowerShell in different ways and integrate them in your scripts to provide some kind of indication. One way is with write-host. You can pass the escape sequence `a  to write host. `a is the Alert corresponding special character:

# play a screech sound (through the internal speaker, not useful on laptops)

write-host "`a";

 

Another way is with a .NET class (.wav format).

# play the file once
$sound = new-Object System.Media.SoundPlayer;
$sound.SoundLocation="c:\WINDOWS\Media\notify.wav";
$sound.Play();

Note that the following process is asynchronously, meaning that the script wont hang until sound has finished playing. This example plays the file repeatedly until a condition met

$sound = new-Object System.Media.SoundPlayer;
$sound.SoundLocation="c:\WINDOWS\Media\notify.wav";
$sound.PlayLooping();
$flag=$false;

1..10 | foreach {
    if($_ -gt 5){$flag=$true} else{sleep -s 1}
    if($flag) { $sound.Stop() }
}

write-host "Done";

There is another class called System.Media.SystemSounds. Pipe the class to get-member to reflect its static members:

 

PS C:\Scripts> [System.Media.SystemSounds] | gm -static

   TypeName: System.Media.SystemSounds

Name            MemberType  Definition
----               ----------         ----------
(...)
Asterisk        Property         static System.Media.SystemSound Asterisk {get;}
Beep             Property         static System.Media.SystemSound Beep {get;}
Exclamation  Property         static System.Media.SystemSound Exclamation {get;}
Hand            Property         static System.Media.SystemSound Hand {get;}
Question       Property         static System.Media.SystemSound Question {get;}

 

Each property emitted represents a system sound type. Now, Pipe each property to get-member

 

PS C:\Scripts> [System.Media.SystemSounds]::Asterisk | gm

   TypeName: System.Media.SystemSound

Name         MemberType   Definition
----            ----------         ----------
(...)
Play           Method           System.Void Play()
ToString    Method           System.String ToString()

 

Great, we can use the Play method,test each line in your console:

[System.Media.SystemSounds]::Asterisk.Play();
[System.Media.SystemSounds]::Beep.Play();
[System.Media.SystemSounds]::Exclamation.Play();
[System.Media.SystemSounds]::Hand.Play();
[System.Media.SystemSounds]::Question.Play();

 

Finally, here is a one-liner for the job. It Utilizes the SoundPlayer(String) Constructor. It Initializes a new instance of the SoundPlayer class, and attaches the specified .wav file.

(new-object Media.SoundPlayer "C:\WINDOWS\Media\notify.wav").play();

Friday, August 31, 2007

List users with email forwarded in Exchange 2007

 

Here's the 2007 on-liner version of Bharat Suneja's post on ExchangepediaBlog. He Explains how to list all users with email being forwarded to another recipient. The sample in file is vbs and is ~35 lines long.

>> get-mailbox | where {$_.ForwardingAddress} | select name, ForwardingAddress, DeliverToMailboxAndForward | format-table -autosize

 

Name                 ForwardingAddress               DeliverToMailboxAndForward
----                    -----------------                      --------------------------
Administrator     homelab.loc/Users/Shay       True
User1                 homelab.loc/Users/User2     False

 

PowerShell is sooooooooo COOL!!!

Thursday, August 30, 2007

Who logged on to my mailbox?

 

This on-liner lists all mailboxes and the user account that was the last to open it.

get-mailbox  | select name, @{n="LastLoggedOnUser";e={(Get-MailboxStatistics -id $_).LastLoggedOnUserAccount}}

 

Name               LastLoggedOnUser
------                ----------------------
Administrator   HOMELAB\Administrator
Shay                 HOMELAB\Shay
User1               HOMELAB\Administrator
User2               HOMELAB\User2
User3               HOMELAB\User3

 

As you can see, the Administrator account was the last user to open User1's mailbox.

 

UPDATED:

Actually here is a better one :)

# ? = where-object
# ft -a = format-table -autosize

>> Get-MailboxStatistics | ? {$_.objectclass -eq "mailbox"} | select DisplayName,Last* | ft -a

 

DisplayName   LastLoggedOnUserAccount   LastLogonTime              LastLogoffTime
-----------        -----------------------             -------------                    --------------
Administrator HOMELAB\Administrator       30/08/2007 12:32:40    30/08/2007 12:51:40
Shay               HOMELAB\Shay                    30/08/2007 12:13:11    30/08/2007 12:43:20
User1             HOMELAB\Administrator       18/05/2007 00:33:40    18/05/2007 00:33:40
User2             HOMELAB\User2                   18/05/2007 00:32:40    18/05/2007 00:32:40
User3             HOMELAB\User3                   18/05/2007 00:31:40    18/05/2007 00:31:40

Saturday, August 25, 2007

Who owns that email address?


Here is a one-liner to find which user owns a specific SMTP address in Exchange 2007.


>> (Get-Mailbox | ? {$_.EmailAddresses -match "^smtp:shay@homelab.loc"}).name
Shay Levi

And as a function


function Get-EmailOwner{
    param([string]$pat)
    $person = (Get-Mailbox | ? {$_.EmailAddresses -match "^smtp:$pat"}).name
    if($person) {$person} else{"No 1"}
}

Tuesday, August 7, 2007

IP decimal to binary conversion and back

 

Just playing around with IP numbers. here are two PowerShell one-liners for the job.

 

$ip = "192.168.0.1";

# convert to binary form
$sbin=[string]::join(".",($ip.split(".") | % {[System.Convert]::ToString($_,2).PadLeft(8,"0")}))   
$sbin


11000000.10101000.00000000.00000001

# convert the result back to decimal
[string]::join(".",($sbin.split(".") | % {[System.Convert]::ToByte($_,2)}))
192.168.0.1

This one-liners can be converted to functions in order to use them in the pipeline thus converting bulk ip numbers easily and PowerShelly ;)

Saturday, December 30, 2006

Chronicles of a Script

In my networking environment, department documents are residing inside a root directory with a name of a four digit year number, one for each year. Underneath, there is a complex directory structure for a various kind of areas, and so on.

As the months go by, new files, directories and sub directories are added. With every beginning of a year, a new directory is created to accommodate the new year files.

Back then, I needed to make a new directory called 2006 and inside of it create the directory tree structure of the 2005 folder. After doing so, users will save their files in the new directory and will navigate their way in a familiar environment while trying to save their files.

This article describes the process as it evolved over time in three ways:

- DOS
- VBScript
- PowerShell

So... i thought to my self, i can copy the 2005 folder to an alternate location, delete all the files in it, and then move the remaining skeleton directories underneath the 2006 folder.
I searched some more and found XCOPY. Running xcopy /? for help revealed its options and completed the solution.

I rejected the first option as being a little dirty and choosed to run XCOPY with some switches. Creating the 2007 folder took no more than a blink.


DOS version

The following XCOPY command will create the same directory structure of c:\windows under c:\testDir (and will create the c:\testDir directory if it doesn't exist).

XCOPY c:\windows c:\testDir /E /T /I

/E - Copies directories and subdirectories, including empty ones.
/T - Creates directory structure, but does not copy files.
/I - Will create the destination directory if it does not exist.

NOTE: if /I is omitted than the console will output this message:
Does C:\testDir specify a file name or directory name on the target(F = file, D = directory)?

This can be tricky if you plan to run the xcopy command inside VBScriptin a hidden window and wait for a return value. The script can hang as its waiting for user input.


VBScript version

A few days later i challenged my self to write a GUI version of it. One that will give me more control over of the process, let the user run it without requiring me to be on the spot and also save it for later use.

Finally, i decided to implement it as a context menu item when right-clicked up on a folder. So, when the user will right click a folder he will find an option called "Copy structure". When selected, the user will be presented with a BrowseForFolder common dialog box asking for the destination directory.


NOTE: To use the script just double-click it and then right-click a folder. You should see an option called Copy Structure, select it. It is best to move the script to a desired location where it wont be accidentally deleted. Then double-click it to update its location in the registry.

You can view the script here


PowerShell version

Finally, while a new year is entering and PS> is building itself as the next scripting environment, here is leveraged version as a one-liner PowerSheel command:

Get-ChildItem $env:windir -recurse | foreach { if($_.PSIsContainer) {New-Item ("d:\testingpath\"+$_.fullname.substring(3,$_.fullname.length-3)).ToString() -itemtype directory -force}}

this command will build the directory structure of c:\windows into d:\testingpath and will create d:\testingpath if it doesn't exist.

11.01.2007 Update:
After two weeks of try and error, here is a shorter one:

Copy-Item $env:windir -filter {$_.PSIsContainer} d:\testingpath -recurse -force

Happy structuring :-)

$hay