Feb 04 2009

More Powershell

Category: Uncategorizedzvolkov @ 9:07 pm

gdr – get list of drives
ni – create new item

To associate .PS1 extension with PowerShell:

PS C:\> set-executionpolicy unrestricted
PS C:\> ni Registry::hkey_classes_root\microsoft.powershellscript.1\shell
PS C:\> ni Registry::hkey_classes_root\microsoft.powershellscript.1\shell\open
PS C:\> ni Registry::hkey_classes_root\microsoft.powershellscript.1\shell\open\command -value ('"' + $PSHOME + '\powershell.exe" -command "& ''%1''"')

then go to Folder options (on XP) and fix Icon for PS1 extensions. Vista requires more registry hacking, so I will post that later

% — is an alias for for-each, so the following prints hello once for each file or folder in the current directory:


PS C:\> ls | % {"hello"}

To pause execution of the script and wait for a key press, add following function at the beginning of your script. then you can use pause command just like you did in DOS:

function Pause ($Message="Press any key to continue...")
{
    Write-Host -NoNewLine $Message
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    Write-Host ""
}

to rename all files in current directory sequentially:


PS C:\> ls | % {$i = 1} {ren $_.name ([string]$i++ + $_.extension)}

cat – outputs content of file as an array of strings

to concatenate all *.csv files in current directory while skipping first line of each file:


PS C:\> ls *.csv | % {$c=cat $_.name;$l=$c.length;$c[2..$l]} > "20090130.csv"