Handling files using Powershell

In this post i have covered about handling files using powershell commands

For below examples i have created flatfile in the path location "D:\myflatfile.txt"
with content as shown below:

Id,Name
1,powershell1.0
2,powershell2.0
3,sqlps
4,sqlcmd


##test whether file exists in that path
Test-Path D:\myflatfile.txt

##reading comma separated values from file
##and storing it in an variable which can hold list of values
$tmptable = @()
$flatfile = Get-Content D:\myflatfile.txt
foreach ( $values in $flatfile )
{
$id=$values.split(",")[0]
$name=$values.split(",")[1]
$tmptable += @{id="${id}";name="$name"}}
$tmptable

##to search particular value in a file
Get-Content D:\myflatfile.txt | Select-String "powershell"

##this is really cool,it displays values as separate column
Import-Csv D:\myflatfile.txt

##To export as CSV
Import-Csv D:\myflatfile.txt | Export-Csv D:\myflatfilecsv.txt

##to append text or date to the end of file
$Appendate= Get-Date; Add-Content D:\*.txt
$Appendate

#to compare two files
$A = D:\myflatfile.txt
$B = D:\myflatfilecsv.txt
Compare-Object $A $B

##to clear content of a file
Clear-Content D:\myflatfilecsv.txt

##deleting all text files,you can also exclude files using -exclude *test*
Remove-Item c:\scripts\* -include *.txt


##using powershell we can rename,copy,move,create & delete files
##save output as HTML,text,csv or xml file



Reference - http://technet.microsoft.com/en-us/library/ee332545.aspx

No comments: