Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Saturday, 31 August 2019

Download all files listed as links in a local TXT file (Powershell Script)



<#

.Synopsis

Downloads files to a folder with the list of urls already stored in a file.

#>

param(

[CmdletBinding()]


[Parameter(mandatory=$true,

Position=0,

ValueFromPipeline=$true,

HelpMessage="The full path of the list file which has the urls of images.")]

[ValidateScript({Test-Path $_})]

[string]$Path,


[Parameter(mandatory=$true,

Position=1,

HelpMessage="The destination folder where images are to be downloaded to.")]

[ValidateNotNullOrEmpty()]

[string]$Destination,


[Parameter(mandatory=$false,

Position=2,

HelpMessage="Select the keywords, images extensions here, each seperated by commas.")]

[ValidateNotNullOrEmpty()]

[string[]]$SelectList,


[Parameter(mandatory=$true,

HelpMessage="Referer url/website.")]

[ValidateNotNullOrEmpty()]

[string]$Referer,


[Parameter(mandatory=$false,

HelpMessage="Select this to download the images at the -Destination folder.")]

[switch]$CustomDirTree=$false

)###param




begin {

$fileDestination=$null

###############################################################################

Function Url-ToPath {<#

.Synopsis

Returns the relative directory/file path for the supplied url, so that it can be used to join

any Windows Directory path.

.Parameter

Select -linux to switch to linux type of path.

#>

param(

[CmdletBinding()]


[Parameter(

mandatory=$true,

Position=0,

ValueFromPipeline=$true,

HelpMessage="The url which will be converted to windows(by default) relative path.")]

[ValidateNotNullOrEmpty()]

[string[]]$Uri,


[Parameter(mandatory=$true,

Position=1,

Helpmessage="Main folder path where the path converted from the url will be joined.")]

[ValidateNotNullOrEmpty()]

[string]$Destination,


[Parameter(

mandatory=$false,

Position=1,

HelpMessage="Select this to convert to linux path instead of windows path.")]

[switch]$linux=$false

)

begin{

[string]$specialChars = "?*`"|<>:"

}

process{

###Removing special char for forming legal path.

$actualLink=$Uri -replace ".*//(.*)",'$1'

$rePattern = ($specialChars.ToCharArray() |ForEach-Object { [regex]::Escape($_) }) -join "|"

$actualLink = $actualLink -replace $rePattern,""

###Applying checks...

$actualLink=$actualLink.TrimEnd()

$actualLink=$actualLink.TrimEnd("/")

$path=$actualLink.TrimStart("/")

$Destination=$Destination.TrimEnd()

$Destination=$Destination.TrimStart()

$Destination=$Destination.TrimEnd("/")

$Destination=$Destination.TrimEnd("\")

if($linux){

$fullPath=([System.IO.Path]::Combine($Destination,$path))

$fullPath=$fullPath -replace "\\","/"

Return $fullPath

}

else{

$fullPath=([System.IO.Path]::Combine($Destination,$path))

$fullPath=$fullPath -replace "/","\"

Return $fullPath

}

}

end{

Remove-Variable specialChars

}

}#######Url-ToPath() ends here.


####################################################################################

Function Download-FileWithProgress {

<#<#<#https://blogs.msdn.microsoft.com/jasonn/2008/06/13/downloading-files-from-the-internet-in-powershell-with-progress/

author:jniver

modified by:picachu

#>#>#>

param(

[CmdletBinding()]


[Parameter(mandatory=$true,Position=0,

HelpMessage="Complete url of file.")]

[ValidateNotNullOrEmpty()]

[string]$Uri,


[Parameter(mandatory=$true,

HelpMessage="Referer url/website.")]

[ValidateNotNullOrEmpty()]

[string]$Referer,


[Parameter(mandatory=$true,Position=1,

HelpMessage="Full path of destination file with name.")]

[ValidateScript({-not (Test-Path $_) })]

[string]$Destination

)

Begin{



}

Process{



###This code bit was inserted by me.

$localTempFilePath=[System.IO.Path]::ChangeExtension($Destination,"temp")

if(Test-Path $localTempFilePath){

try{

Remove-Item $localTempFilePath

}

catch{

Return $false

}

}

elseif(-not (Test-Path ([IO.Path]::GetDirectoryName($Destination)))){

New-Item ([IO.Path]::GetDirectoryName($Destination)) -ItemType Directory -Verbose -InformationAction Continue | Out-Null

}

####above code bit was inserted by me.

$uriObject = New-Object "System.Uri" "$Uri"

$request = [System.Net.HttpWebRequest]::Create($uriObject)

if(-not [string]::IsNullOrWhiteSpace($Referer)){

$request.Referer="$Referer"

}

$request.set_Timeout(6000) #15 second timeout

$response = $request.GetResponse()

if(-not [string]::IsNullOrEmpty($response)){

$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)

###Write-Output "Length is $totalLength KB"

$responseStream = $response.GetResponseStream()

$responseStream.ReadTimeout=60000###60sec

<#<#<##############Appended codes

Problem with the code when the download file is less than 1024 bytes.

Corrected by doing an If/else statement that checks for file length less than 1024:

#>#>#>

$responseContentLength = $response.get_ContentLength()

if(-not ($responseContentLength -lt 1024))

{

$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)

}

else

{

$totalLength = [System.Math]::Floor(1024/1024)

}

#######Appended codes end here

$targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $localTempFilePath, Create

$buffer = new-object byte[] 10KB

try{

$count = $responseStream.Read($buffer,0,$buffer.length)

$downloadedBytes = $count

while ($count -gt 0)

{

$targetStream.Write($buffer, 0, $count)

$count = $responseStream.Read($buffer,0,$buffer.length)

$downloadedBytes = $downloadedBytes + $count

###[System.Math]::Floor($downloadedBytes/1024)

Write-Progress -activity "Downloading file '$($Uri.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength) * 100)



}

}

finally{

$targetStream.Flush()

$targetStream.Close()

$targetStream.Dispose()

$responseStream.Dispose()

}

Write-Progress -activity "Finished downloading file '$($Uri.split('/') | Select -Last 1)'"

Return $true

}###if

else{

Return $false

}

}###Process

End{



if(($totalLength -eq [System.Math]::Floor($downloadedBytes/1024)) -and (0 -ne $downloadedBytes)){

Move-Item -Path $localTempFilePath -Destination $Destination

}

Remove-Variable "uriObject"

if($response){

Remove-Variable response

}

Remove-Variable "request"

}

}###########Download-FileWithProgress() ends here.


}###begin

process {

Write-Information -MessageData "`n--------------->Beginning Download session of $Path" -Verbose -InformationAction Continue

foreach($url in Get-Content $Path){

$url=$url.TrimEnd()

$filePath=Url-ToPath -Uri $url -Destination $Destination

$fileName=([System.IO.Path]::GetFileName($filePath))

[String]$folderName=([System.IO.Path]::GetFileNameWithoutExtension($Path))

$folderName = $folderName.Replace("List","")

$customFilePath=([System.IO.Path]::Combine($Destination,$folderName,$fileName))

if($CustomDirTree){


if(-not (Test-Path ([System.IO.Path]::GetDirectoryName($customFilePath)))){

New-Item -Path ([System.IO.Path]::GetDirectoryName($customFilePath)) -ItemType Directory | Out-Null

}

if(Test-Path $filePath){Copy-Item -Path $filePath -Destination $customFilePath}

$fileDestination = $customFilePath


}

else{

if(-not (Test-Path ([System.IO.Path]::GetDirectoryName($filePath)))){

New-Item -Path ([System.IO.Path]::GetDirectoryName($filePath)) -ItemType Directory | Out-Null

}

if(Test-Path $customFilePath){Copy-Item -Path $customFilePath -Destination $filePath}

$fileDestination = $filePath

}



if(-not (Test-Path $fileDestination)){

Write-Information -MessageData "Downloading to $fileDestination" -Verbose -InformationAction Continue

###Command for downloading.

if([string]::IsNullOrWhiteSpace($Referer)){

Download-FileWithProgress -Uri $url -Destination $fileDestination

}

else{

Download-FileWithProgress -Uri $url -Destination $fileDestination -Referer $url

}

###Invoke-WebRequest -Uri $url -UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::Chrome)

###.\Download-WithReferer.ps1 -Url $url -Destination $filePath

}

else{

Write-Information -MessageData "$fileDestination Already exist." -Verbose -InformationAction Continue

}

}###foreach()

}###Process

end {



}

Monday, 26 March 2018

Search Images in a Webpage Using Powershell.

Search-RemoteImages.ps1

<#
.Sysnopsis
    This cmdlet fetches all the urls of the photos in a webpage.
    The output/resulting list file has a final extension of "List.txt" as in "filenameList.txt"
#>

param(
[CmdletBinding()]

    [Parameter(mandatory=$true,
    Position=0,
    HelpMessage="The url of a webpost which has the images shown.")]
    [ValidateNotNullOrEmpty()]
[string]$Uri,

    [Parameter(mandatory=$true,
    Position=1,
    HelpMessage="The destination folder where images list are to be saved to.")]
    [ValidateNotNullOrEmpty()]
[string]$Destination,

[Parameter(mandatory=$false,
HelpMessage="Select this to delete previous list file.")]
[switch]$DeletePrevious=$false
)###param

    $relativeFilePath=.\Url-ToPath.ps1 -Uri "$Uri"
    $relativeFilePath=([System.IO.Path]::ChangeExtension($relativeFilePath,"txt"))
    $imagesListFile=[System.IO.Path]::Combine($Destination,$relativeFilePath)
    if(($DeletePrevious) -and (Test-Path "$imagesListFile")){
        Remove-Item "$imagesListFile" | Out-Null
        }
        elseif(Test-Path "$imagesListFile"){
            ###Write-Verbose -Message "Images list file already exist." -Verbose
            Return "$imagesListFile"
        }
    $info=[System.Net.WebRequest]::Create("$Uri")
    $info.UserAgent=([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer)
    $info.Timeout=6000;#6secs max
TRY{
    ###Write-Verbose -Message "Fetching image urls..." -Verbose
    $storedStatus=$info.GetResponse()
    $storedStatus.Close()
    if([string]::Equals("OK",$storedStatus.StatusCode)){
        ###Write-Output "GOOD"
        $iwr=Invoke-WebRequest -Uri "$Uri" -UseBasicParsing
        $images=$iwr.Images | select src
        $list=$images###.ToString()
        if(-not (Test-Path ([System.IO.Path]::GetDirectoryName("$imagesListFile")))){
            New-Item -Path ([System.IO.Path]::GetDirectoryName("$imagesListFile")) -ItemType Directory | Out-Null
        }
        Write-Output $list >> "$imagesListFile"
        Return "$imagesListFile"
    }
}
FINALLY{
    Remove-Variable "relativeFilePath"
    Remove-Variable "imagesListFile"
    }

Sunday, 25 March 2018

Remove or Replace Substrings From the List Using Powershell.

 Remove-Text.ps1

<#
.Synopsis
    Created especially to Convert the url-links of thumbnails to url-links of the actual files.
The values in -RemoveList are removed/replaced with value of -Substitute in the input-links.
Change the value of -RemoveList and -Substitute to adjust for each situation.
#>
param(
            [Parameter(mandatory=$true,
            Position=0,
            HelpMessage="The full path of the file which is to be edited.")]
            [ValidateNotNullOrEmpty()]
            [ValidateScript({Test-Path $_})]
    [string]$Path,

            [Parameter(
            mandatory=$false,
            Position=1,
            HelpMessage="Destination list file full path.")]
            [ValidateNotNullOrEmpty()]
            [ValidateScript({-not (Test-Path $_)})]
            [ValidateScript({-not $PSBoundParameters['ReplaceOriginal']})]
    [string]$Destination,

            [Parameter(
            Position=2,
            HelpMessage="Enter one or more strings as keywords to be replaced in the lines content of the file.")]
            [ValidateNotNullOrEmpty()]
    [string[]]$RemoveList='Thum/Thum-',

            [Parameter(
            Position=3,
            HelpMessage="Enter one or more strings as keywords for substituting the keywords in the lines content of the file.")]
            [ValidateNotNullOrEmpty()]
    [string[]]$Substitute="",

            [Parameter(
            mandatory=$false,
            HelpMessage="Select this to replace original file by the output file.")]
            [ValidateScript({[string]::IsNullOrWhiteSpace($PSBoundParameters['Destination'])})]
    [switch]$ReplaceOriginal=$false
    )
Process{
    $tempFilePath=$Path -replace ".txt","Temp.txt"
    if($false -ieq (Test-Path "$Path")){
        Return "List file does not exist."
        }
        else{
            foreach($keyword in $RemoveList){
                if(-not [string]::IsNullOrWhiteSpace($keyword)){
                    foreach($thumbnailLink in Get-Content "$Path"){
                        ###$thumbnailLink = $thumbnailLink.Replace($keyword,$Substitute)
                        $thumbnailLink = $thumbnailLink -replace $keyword,$Substitute
                        Write-Output $thumbnailLink >> $tempFilePath
                    }
                    Write-Information -MessageData  "Text $keyword removed from lines." -Verbose -InformationAction Continue
                }###if
           
            }###foreach()
        }###else
    if($ReplaceOriginal){
            Remove-Item $Path | Out-Null
            Rename-Item $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path)) | Out-Null
            }
            else{
                Move-Item -Path $tempFilePath -Destination $Destination | Out-Null
            }
 }
 end{
        Remove-Variable "tempFilePath"
    }

Friday, 23 March 2018

my Powershell Version

 Version:
> $psversiontable                                                           
PSVersion                      5.1.14393.1944
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.1944
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1 

Reject Lines From List in a File Using Powershell.

Reject-Lines.ps1
<#
.Synopsis
    Rejects only the lines containing the value of the $Substring from the list
fetched from the file $Path. The result is stored in -Destination file path.
#>
param (
        [Parameter(mandatory=$true,
        Position=0,
        HelpMessage="The list file which contains the list for Rejecting wanted lines.")]
        [ValidateScript({Test-Path $_})]
        [string]$Path,

        [Parameter(mandatory=$false,
        Position=1,
        HelpMessage="The destination file path where the list will be stored. It should not exist.
        If it may exist and you want to replace it, the use -DeletePrevious switch")]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({-not $PSBoundParameters['ReplaceOriginal']})]
        [string]$Destination,

        [Parameter(mandatory=$false,
        Position=2,
        HelpMessage="The lines containing this string are Rejected. Accepts only a single string.")]
        [ValidateNotNullOrEmpty()]
        [string]$Substring,

        [Parameter(mandatory=$false,
        HelpMessage="Select this to delete previous existing -Destination file")]
        [switch]$DeletePrevious=$false,

        [Parameter(mandatory=$false,
        HelpMessage="Select this to delete the original file after processing.")]
        [ValidateScript({-not [string]::IsNullOrWhiteSpace($Destination)})]
        [switch]$DeleteOriginal=$false,
       
        [Parameter(mandatory=$false,
        HelpMessage="Select this to replace the original file with the resulting file.")]
        [ValidateScript({[string]::IsNullOrWhiteSpace($PSBoundParameters['Destination'])})]
        [switch]$ReplaceOriginal=$false
        )
Begin{
    if(($ReplaceOriginal) -and (-not [string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Result will be stored in the original file name. Destination file will not be created." -Verbose -InformationAction Continue
    }
    elseif(($DeleteOriginal) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Valid Destination file path should be entered if original file is to be deleted."  -Verbose -InformationAction Continue
    }
    elseif(($DeletePrevious) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Use and enter Destination file path to avoid replacing the original file."  -Verbose -InformationAction Continue
    }
}###begin
Process{
    ###Specifies default file management of original file.
        if(([string]::IsNullOrWhiteSpace($Destination))-and (-not ($ReplaceOriginal -or $DeleteOriginal -or $DeletePrevious))){
            Write-Warning -Message "Specify -Destination to avoid loss of data or -ReplaceOriginal. Exiting..."  -Verbose -InformationAction Continue
            Return $null
        }
    if((-not [string]::IsNullOrWhiteSpace($Path)) -and ($false -ieq (Test-Path "$Path"))){
        Write-Error -Message "List file for Rejecting lines does not exist." -Verbose -InformationAction Continue
        Return $null
    }
    elseif(($DeletePrevious) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Exiting to avoid loss of data."  -Verbose -InformationAction Continue
        Return $null
    }
    if(($DeletePrevious) -and (-not [string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path $Destination)){
        Remove-Item $Destination | Out-Null
    }
    elseif((-not [string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path "$Destination")){
        Write-Warning -Message "Previous '$Destination' file already exist. Cancelling line Rejection." -Verbose -InformationAction Continue
        Return $null
    }
    if($ReplaceOriginal){
        $tempFilePath=$Path -replace ".txt","Temp.txt"
    }
    elseif(-not [string]::IsNullOrWhiteSpace($Destination)){
        $tempFilePath=$Destination -replace ".txt","Temp.txt"
    }
    if((-not [string]::IsNullOrWhiteSpace($tempFilePath)) -and (Test-Path $tempFilePath)){
        Remove-Item $tempFilePath | Out-Null
    }
    ##############################Reading list
    if(-not [string]::IsNullOrWhiteSpace($Substring)){
        foreach($line in Get-Content "$Path")
        {
            if($line -inotmatch [regex]::Escape($substring)){
                Write-Output $line >> "$tempFilepath"
            }
        }###foreach $line
    ################################Reading done.
if($ReplaceOriginal){
            Remove-Item $Path
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path))
        }
        elseif($DeleteOriginal){
            Move-Item -Path $tempFilePath -Destination $Destination
            ###Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Destination))
            Remove-Item -Path $Path | Out-Null
        }
        <#
        elseif(($DeletePrevious)-and ([string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path $Path)){
            Remove-Item $Path
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path))
        }
        #>
        else{
            Move-Item -Path $tempFilePath -Destination $Destination
            ###Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Destination))
        }
        Write-Information -MessageData "Lines with '$Substring' in the file have been Rejected." -Verbose -InformationAction Continue
    }
    else
    {
        Write-Information -MessageData "Lines Rejection canceled." -Verbose -InformationAction Continue
    }
}###Process

Select Lines From List in a File Using Powershell.

Select-Lines.ps1
<#
.Synopsis
    Selects only the lines containing the value of the $Substring from the list
fetched from the file $Path. The result is stored in -Destination file path.
#>
param (
        [Parameter(mandatory=$true,
        Position=0,
        HelpMessage="The list file which contains the list for Selecting wanted lines.")]
        [ValidateScript({Test-Path $_})]
        [string]$Path,

        [Parameter(mandatory=$false,
        Position=1,
        HelpMessage="The destination file path where the list will be stored. It should not exist.
        If it may exist and you want to replace it, the use -DeletePrevious switch")]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({-not $PSBoundParameters['ReplaceOriginal']})]
        [string]$Destination,

        [Parameter(mandatory=$false,
        Position=2,
        HelpMessage="The lines containing this string are Selected. Accepts only a single string.")]
        [ValidateNotNullOrEmpty()]
        [string]$Substring,

        [Parameter(mandatory=$false,
        HelpMessage="Select this to delete previous existing -Destination file")]
        [switch]$DeletePrevious=$false,

        [Parameter(mandatory=$false,
        HelpMessage="Select this to delete the original file after processing.")]
        [ValidateScript({-not [string]::IsNullOrWhiteSpace($Destination)})]
        [switch]$DeleteOriginal=$false,
       
        [Parameter(mandatory=$false,
        HelpMessage="Select this to replace the original file with the resulting file.")]
        [ValidateScript({[string]::IsNullOrWhiteSpace($PSBoundParameters['Destination'])})]
        [switch]$ReplaceOriginal=$false
        )
Begin{
    if(($ReplaceOriginal) -and (-not [string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Result will be stored in the original file name. Destination file will not be created." -Verbose -InformationAction Continue
    }
    elseif(($DeleteOriginal) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Valid Destination file path should be entered if original file is to be deleted."  -Verbose -InformationAction Continue
    }
    elseif(($DeletePrevious) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Use and enter Destination file path to avoid replacing the original file."  -Verbose -InformationAction Continue
    }
}###begin
Process{
    ###Specifies default file management of original file.
        if(([string]::IsNullOrWhiteSpace($Destination))-and (-not ($ReplaceOriginal -or $DeleteOriginal -or $DeletePrevious))){
            Write-Warning -Message "Specify -Destination to avoid loss of data or -ReplaceOriginal. Exiting..."  -Verbose -InformationAction Continue
            Return $null
        }
    if((-not [string]::IsNullOrWhiteSpace($Path)) -and ($false -ieq (Test-Path "$Path"))){
        Write-Error -Message "List file for Selecting lines does not exist." -Verbose -InformationAction Continue
        Return $null
    }
    elseif(($DeletePrevious) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Exiting to avoid loss of data."  -Verbose -InformationAction Continue
        Return $null
    }
    if(($DeletePrevious) -and (-not [string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path $Destination)){
        Remove-Item $Destination | Out-Null
    }
    elseif((-not [string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path "$Destination")){
        Write-Warning -Message "Previous '$Destination' file already exist. Cancelling line Selection." -Verbose -InformationAction Continue
        Return $null
    }
    if($ReplaceOriginal){
        $tempFilePath=$Path -replace ".txt","Temp.txt"
    }
    elseif(-not [string]::IsNullOrWhiteSpace($Destination)){
        $tempFilePath=$Destination -replace ".txt","Temp.txt"
    }
    if((-not [string]::IsNullOrWhiteSpace($tempFilePath)) -and (Test-Path $tempFilePath)){
        Remove-Item $tempFilePath | Out-Null
    }
    ##############################Reading list
    if(-not [string]::IsNullOrWhiteSpace($Substring)){
        foreach($line in Get-Content "$Path")
        {
            if($line -imatch [regex]::Escape($substring)){
                Write-Output $line >> "$tempFilepath"
            }
        }###foreach $line
    ###############################Reading done.
        if($ReplaceOriginal){
            Remove-Item $Path
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path))
        }
        elseif($DeleteOriginal){
            Move-Item -Path $tempFilePath -Destination $Destination
            ###Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Destination))
            Remove-Item -Path $Path | Out-Null
        }
        <#
        elseif(($DeletePrevious)-and ([string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path $Path)){
            Remove-Item $Path
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path))
        }
        #>
        else{
            Move-Item -Path $tempFilePath -Destination $Destination
            ###Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Destination))
        }
        Write-Information -MessageData "Lines with '$Substring' in the file have been Selected." -Verbose -InformationAction Continue
    }
    else
    {
        Write-Information -MessageData "Lines Selection canceled." -Verbose -InformationAction Continue
    }
}###Process

Thursday, 22 March 2018

Convert Uri To Complete Local Directory Path.

<#
.Syntax
    Url-ToPath.ps1 -Uri <string[]> -Destination <string> [-linux]
.Synopsis
    The return value is: supplied -Uri converted to local file system path and joined to -Destination folder path, which can be
    any Windows/Linux Directory path.
.Parameter
    -Uri :The url which is to be mapped to the local system.
    -Destination :The folder/directory path where the conveted url will be mapped.
    -linux :For Linux system.
#>
param(
    [CmdletBinding()]

    [Parameter(
    mandatory=$true,
    Position=0,
    ValueFromPipeline=$true,
    HelpMessage="The url which will be converted to windows(by default) relative path.")]
    [ValidateNotNullOrEmpty()]
    [string[]]$Uri,

    [Parameter(mandatory=$true,
    Position=1,
    Helpmessage="Main folder path where the path converted from the url will be joined.")]
    [ValidateNotNullOrEmpty()]
    [string]$Destination,

    [Parameter(
    mandatory=$false,
    Position=1,
    HelpMessage="Select this to convert to linux path instead of windows path.")]
    [switch]$linux=$false
    )
    begin{
        [string]$specialChars = "?*`"|<>:"
    }
    process{
        ###Removing special char for forming legal path.
        $actualLink=$Uri -replace ".*//(.*)",'$1'
        $rePattern = ($specialChars.ToCharArray() |ForEach-Object { [regex]::Escape($_) }) -join "|"
        $actualLink = $actualLink -replace $rePattern,""
        ###Applying checks...
        $actualLink=$actualLink.TrimEnd()
        $actualLink=$actualLink.TrimEnd("/")
        $path=$actualLink.TrimStart("/")
        $Destination=$Destination.TrimEnd()
        $Destination=$Destination.TrimStart()
        $Destination=$Destination.TrimEnd("/")
        $Destination=$Destination.TrimEnd("\")
        if($linux){
            $fullPath=([System.IO.Path]::Combine($Destination,$path))
            $fullPath=$fullPath -replace "\\","/"
            Return $fullPath
        }
        else{
            $fullPath=([System.IO.Path]::Combine($Destination,$path))
            $fullPath=$fullPath -replace "/","\"
            Return $fullPath
        }
    }
    end{
        Remove-Variable specialChars
    }

Wednesday, 21 March 2018

Move Items to Recycle Bin Using Powershell

Recycle-ToBin.ps1
<#
.Synopsis
    This cmdlet moves item to Recycle Bin instead of deleting them permanently.
    It is useful while operating in an untested or partially tested environment.
#>
param(

[Parameter(mandatory=$true)]
$Path
)
    Add-Type -AssemblyName Microsoft.VisualBasic
    $item = Get-Item -Path $Path -ErrorAction SilentlyContinue
    if ($item -eq $null)
    {
        Write-Error("'{0}' not found" -f $Path)
    }
    else
    {
        $fullpath=$item.FullName
        Write-Information("Moving '{0}' to the Recycle Bin" -f $fullpath) -Verbose -InformationAction Continue
        if (Test-Path -Path $fullpath -PathType Container)
        {
            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
        }
        else
        {
            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
        }
    }

Tuesday, 20 March 2018

Sorting a list to Unique and Order.

<#
.Synopsis
    Sorts a list file content, and removes duplicate line from the list, keeping only one instance of the line.
    Replaces the original file by default.
#>
param (
    [CmdletBinding()]
    [Parameter(
    mandatory=$true,
    Position=0,
    HelpMessage="The source file path containing the list to be sorted.")]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({Test-Path $_})]
    [string]$Path,

    [Parameter(
    mandatory=$false,
    Position=1,
    HelpMessage="Provide value for this to get the sorted list in a different file.")]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({-not (Test-Path $_)})]
    [ValidateScript({-not $ReplaceOriginal})]
    [string]$Destination,

    [Parameter(
    mandatory=$false,
    HelpMessage="Select this to delete the original source file after procesiing.")]
    [ValidateScript({-not [string]::IsNullOrWhiteSpace($Destination)})]
    [switch]$DeleteOriginal=$false,

    [Parameter(
    mandatory=$false,
    HelpMessage="Select this to remove -Destination file if it already exist.")]
    [switch]$DeletePrevious=$false,

    [Parameter(
    mandatory=$false,
    HelpMessage="Select this to replace the source file by the resulting file with same name.")]
    [ValidateScript({[string]::IsNullOrWhiteSpace($Destination) })]
    [switch]$ReplaceOriginal=$false
    )

    Begin{
        if(($ReplaceOriginal) -and (-not [string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Result will be stored in the original file name. Destination file will not be created." -Verbose -InformationAction Continue
    }
    elseif(($DeleteOriginal) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Valid Destination file path should be entered if original file is to be deleted."  -Verbose -InformationAction Continue
    }
    elseif(($DeletePrevious) -and ([string]::IsNullOrWhiteSpace($Destination))){
        Write-Warning -Message "Use and enter Destination file path to avoid replacing the original file."  -Verbose -InformationAction Continue
    }
    }
    Process{
        if((-not [string]::IsNullOrWhiteSpace($Path)) -and ($false -ieq (Test-Path "$Path"))){
            Write-Error -Message "List file for Sorting lines does not exist." -Verbose -InformationAction Continue
            Return $null
        }
        elseif(($DeletePrevious) -and ([string]::IsNullOrWhiteSpace($Destination))){
            Write-Warniing -Message "Exiting to avoid replacing original file."  -Verbose -InformationAction Continue
            Return $null
        }
        if(($DeletePrevious) -and (-not [string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path $Destination)){
            Remove-Item $Destination | Out-Null
        }
        elseif((-not [string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path "$Destination")){
            Write-Warning -Message "Previous '$Destination' file already exist. Cancelling line Rejection." -Verbose -InformationAction Continue
            Return $null
        }
        if($ReplaceOriginal){
            $tempFilePath=$Path -replace ".txt","Temp.txt"
        }
        elseif(-not [string]::IsNullOrWhiteSpace($Destination)){
            $tempFilePath=$Destination -replace ".txt","Temp.txt"
        }
        if((-not [string]::IsNullOrWhiteSpace($tempFilePath)) -and (Test-Path $tempFilePath)){
            Remove-Item $tempFilePath | Out-Null
        }
        ##################Reading list.
        Get-Content $Path | sort | get-unique >> $tempFilePath
        ################################Reading done.
        if($ReplaceOriginal){
            Remove-Item $Path
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path))
        }
        elseif($DeleteOriginal){
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Destination))
            Remove-Item -Path $Path | Out-Null
        }
        <#
        elseif(($DeletePrevious)-and ([string]::IsNullOrWhiteSpace($Destination)) -and (Test-Path $Path)){
            Remove-Item $Path
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path))
        }
        #>
        else{
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Destination))
        }
        <#
        if($ReplaceOriginal)
        {
            Remove-Item $Path
            Rename-Item -Path $tempFilePath -NewName ([System.IO.Path]::GetFileName($Path))
        }
        elseif($DeleteOriginal){
            if((Test-Path $Path) -and ([string]::IsNullOrWhiteSpace($Destination))){
                Remove-Item $Path | Out-Null
                Move-Item $tempFilePath -Destination $Path | Out-Null
            }
            elseif(-not [string]::IsNullOrWhiteSpace($Destination)){
                Move-Item $tempFilePath -Destination $Destination | Out-Null
            }
        }
        else{
            if(-not [string]::IsNullOrWhiteSpace($Destination)){
                Move-Item $tempFilePath -Destination $Destination | Out-Null
            }
        }
        #>
        Write-Information -MessageData "$Path  file is Uniquely sorted." -InformationAction Continue -Verbose
    }
    End{
       
        Remove-Variable "tempFilePath"
       
    }

Sunday, 18 March 2018

Downloading a File With Progress Bar.


        <#
        .Synopsis
            This cmdlet downloads a remote file to the local destination target all the while showing the progress and size of the download.
        .Reference
            https://blogs.msdn.microsoft.com/jasonn/2008/06/13/downloading-files-from-the-internet-in-powershell-with-progress/
        author:jniver
        modified by:picachu010
        #>
        param(
            [CmdletBinding()]

            [Parameter(mandatory=$true,Position=0,
            HelpMessage="Complete url of file.")]
            [ValidateNotNullOrEmpty()]
            [string]$Uri,

            [Parameter(mandatory=$true,
            HelpMessage="Referer url/website.")]
            [ValidateNotNullOrEmpty()]
            [string]$Referer,

            [Parameter(mandatory=$true,Position=1,
            HelpMessage="Full path of destination file with name.")]
            [ValidateScript({-not (Test-Path $_) })]
            [string]$Destination
            )
            Begin{
      
               }
            Process{
          
               ###This code bit was inserted by me.
               $localTempFilePath=[System.IO.Path]::ChangeExtension($Destination,"temp")
               if(Test-Path $localTempFilePath){
                    try{
                        Remove-Item $localTempFilePath
                    }
                    catch{
                        Return $false
                        }
               }
               elseif(-not (Test-Path ([IO.Path]::GetDirectoryName($Destination)))){
                    New-Item ([IO.Path]::GetDirectoryName($Destination)) -ItemType Directory  -Verbose -InformationAction Continue | Out-Null
               }
               ####above code bit was inserted by me.
               $uriObject = New-Object "System.Uri" "$Uri"
               $request = [System.Net.HttpWebRequest]::Create($uriObject)
               if(-not [string]::IsNullOrWhiteSpace($Referer)){
                   $request.Referer="$Referer"
                   }
               $request.set_Timeout(6000) #15 second timeout
               $response = $request.GetResponse()
               if(-not [string]::IsNullOrEmpty($response)){
                   $totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
                   ###Write-Output "Length is $totalLength KB"
                   $responseStream = $response.GetResponseStream()
                   $responseStream.ReadTimeout=60000###60sec
                    <#<#<##############Appended codes
                    Problem with the code when the download file is less than 1024 bytes.
                     Corrected by doing an If/else statement that checks for file length less than 1024:
                    #>#>#>
                       $responseContentLength = $response.get_ContentLength()
                        if(-not ($responseContentLength -lt 1024))
                        {
                           $totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
                        }
                        else
                        {
                           $totalLength = [System.Math]::Floor(1024/1024)
                        }
                    #######Appended codes end here
                   $targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $localTempFilePath, Create
                   $buffer = new-object byte[] 10KB
                   try{
                   $count = $responseStream.Read($buffer,0,$buffer.length)
                   $downloadedBytes = $count
                       while ($count -gt 0)
                       {
                           $targetStream.Write($buffer, 0, $count)
                           $count = $responseStream.Read($buffer,0,$buffer.length)
                           $downloadedBytes = $downloadedBytes + $count
                           ###[System.Math]::Floor($downloadedBytes/1024)
                           Write-Progress -activity "Downloading file '$($Uri.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength)  * 100)
                  
                       }
                    }
                    finally{
                        $targetStream.Flush()
                        $targetStream.Close()
                        $targetStream.Dispose()
                        $responseStream.Dispose()
                    }
                   Write-Progress -activity "Finished downloading file '$($Uri.split('/') | Select -Last 1)'"
                   Return $true
               }###if
               else{
                    Return $false
               }
            }###Process
            End{
                  
                if(($totalLength -eq [System.Math]::Floor($downloadedBytes/1024)) -and (0 -ne $downloadedBytes)){
                        Move-Item -Path $localTempFilePath -Destination $Destination
               }
                Remove-Variable "uriObject"
                if($response){
                    Remove-Variable response
                }
                Remove-Variable "request"
            }
       

Sorting a list to Unique and Order.

<#
.Synopsis
        Checking remote link, like pinging, for availability of a link.
        This function does not give any output to any output device.
        It can only return true or false.
#>
        param (
            [Parameter(mandatory=$true)]
            [ValidateNotNullOrEmpty()]
            [string]$Url
            )
        begin{
            New-Variable -Name "info"
            New-Variable -Name "storedStatus"
        }
        process{
            $info = [System.Net.WebRequest]::Create("$Url")
            $info.UserAgent = ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer)
            $info.Timeout = 6000; # 6 secs max
            Write-Information -MessageData "Checking url -> $Url" -Verbose -InformationAction Continue
            $storedStatus = $info.GetResponse()
            ###Uncomment for debugging.
            ###$storedStatus
            try{
                $storedStatus.Close() | Out-Null
            }
            catch{
                return $false
            }
            if(("OK" -ieq $storedStatus.StatusCode) -or ("200" -ieq $storedStatus.StatusCode)){
                return $true
            }
            else{
                return $false
            }
        }
        end{
            Remove-Variable -Name "info"
            Remove-Variable -Name "storedStatus"
        }