Unzipping ZIP Files with PowerShell 3.0 and 4.0

ZIP file support was introduced in PowerShell 5.0, but if you have installed the .NET Framework 4.5 and possibly want more control over the unzipping process, try this:

#requires -Version 2
# .NET Framework 4.5 required!

Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop

$Source = 'C:\somezipfile.zip'
$Destination = 'C:\somefolder'
$Overwrite = $true
$ShowDestinationFolder = $true

if ((Test-Path $Destination) -eq $false) 
{
 $null = mkdir $Destination 
}

$Content = [IO.Compression.ZipFile]::OpenRead($Source).Entries
$Content | 
 ForEach-Object -Process {
    $FilePath = Join-Path -Path $Destination -ChildPath $_
                [IO.Compression.ZipFileExtensions]::ExtractToFile($_,$FilePath,$Overwrite)
            }
if ($ShowDestinationFolder) 
{
 explorer.exe $Destination 
}

Twitter This Tip! ReTweet this Tip!

Wednesday, July 29, 2015
Posted by AsifSaif

Unzipping ZIP Files

In PowerShell 5.0, there is a new cmdlet that can unzip ZIP files:

#requires -Version 5


$Source = 'C:\somezipfile.zip'
$Destination = 'C:\somefolder'
$Overwrite = $true
$ShowDestinationFolder = $true

Expand-Archive -Path $Source -DestinationPath $Destination -Force:$Overwrite

if ($ShowDestinationFolder) 
{
  explorer.exe $Destination
}

Twitter This Tip! ReTweet this Tip!

Tuesday, July 28, 2015
Posted by AsifSaif

Finding Computers with PowerShell Remoting

In a previous tip we showed how you can test the network port of a computer. When you have installed the free RSAT tools from Microsoft, you could query your Active Directory and get a list of all computer accounts, or all computer accounts in a given scope (use –SearchBase to limit the search results to a specific OU for example).

Next, you could use the port test to see whether these computers are online and have the PowerShell remoting port 5985 open:

#requires -Version 1 -Modules ActiveDirectory
function Test-Port
{
    Param([string]$ComputerName,$port = 5985,$timeout = 1000)
 
    try
    {
        $tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
        $iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
        $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
        if(!$wait)
        {
            $tcpclient.Close()
            return $false
        }
        else
        {
            # Close the connection and report the error if there is one
            
            $null = $tcpclient.EndConnect($iar)
            $tcpclient.Close()
            return $true
        }
    }
    catch 
    {
        $false 
    }
}


Get-ADComputer -Filter * | 
Select-Object -ExpandProperty dnsHostName |
ForEach-Object {
    Write-Progress -Activity 'Testing Port' -Status $_
} |
Where-Object -FilterScript {
    Test-Port -ComputerName $_ 
}

Twitter This Tip! ReTweet this Tip!

Monday, July 27, 2015
Posted by AsifSaif

Testing a Network Port

To see whether you can access a remote computer via a given network port, here is a test function called Test-Port; it takes a remote computer name (or IP address), and optionally a port number and timeout.

The default port is 5985 which is used for PowerShell remoting. The default timeout is 1000ms (1 second).

#requires -Version 1
function Test-Port
{
    Param([string]$ComputerName,$port = 5985,$timeout = 1000)
 
    try
    {
        $tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
        $iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
        $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
        if(!$wait)
        {
            $tcpclient.Close()
            return $false
        }
        else
        {
            # Close the connection and report the error if there is one
            
            $null = $tcpclient.EndConnect($iar)
            $tcpclient.Close()
            return $true
        }
    }
    catch 
    {
        $false 
    }
}

So if you’d like to know if a remote computer is enabled for PowerShell remoting, you could simply run:

 
PS> Test-Port -ComputerName TestServer 
False
 

With the default timeout of 1 second, you would have to wait at most 1 second for a response.

Twitter This Tip! ReTweet this Tip!

Friday, July 24, 2015
Posted by AsifSaif

Finding Logged On Users

In a previous tip we explained how you find the physically logged on user. In this tip you will see how you can list the current logon sessions, reporting all users who are currently logged on to a system. This includes users that are connected via RDP and other means:

#requires -Version 1
function Get-LoggedOnUserSession
{
    param
    (
        $ComputerName,
        $Credential
    )

    Get-WmiObject -Class Win32_LogonSession @PSBoundParameters |
    ForEach-Object {
        $_.GetRelated('Win32_UserAccount') |
        Select-Object -ExpandProperty Caption 
    } |
    Sort-Object -Unique
}

When you run Get-LoggedOnUserSession, you get back all users that are currently connected to your machine. Specify the -ComputerName and optionally the -Credential (domain\username) parameters to access remote machines.

Twitter This Tip! ReTweet this Tip!

Thursday, July 23, 2015
Posted by AsifSaif

Find Physically Logged On User

There can always be only one physically logged on user on a machine. The physically logged on user is the one sitting right at the machine.

Here is a PowerShell function that reports the physically logged on person for a local or remote system. To access a remote system, you would need local Administrator privileges on the remote machine, and make sure your firewalls are configured correctly to let you connect.

#requires -Version 1
function Get-LoggedOnUser
{
    param
    (
        $ComputerName,
        $Credential
    )

    Get-WmiObject -Class Win32_ComputerSystem @PSBoundParameters |
    Select-Object -ExpandProperty UserName
}

Once you run Get-LoggedOnUser, you get back the name of the physically logged on user on the local machine. Use the –ComputerName (and optionally –Credential) parameters to access a remote machine.

Twitter This Tip! ReTweet this Tip!

Wednesday, July 22, 2015
Posted by AsifSaif

Accessing an SQL Database with a Connection String

In a previous tip we explained how you can construct the connection string to a SQL database. Whether you use this to create the connection string, or whether you create a connection string from scratch does not matter – provided you have a valid connection string to a database, then this example will illustrate how you can submit SQL commands to the database.

#requires -Version 2

# make sure this is a valid connection string to your database
# see http://ift.tt/RBKpAW for reference
$connectionString = 'Provider=SQLOLEDB.1;Password=.topSecret!;Persist Security 
 Info=True;User ID=sa;Initial Catalog=test;Data Source=myDBServer\SQLEXPRESS2012'

# make sure this is valid SQL for your database
# so in this case, make sure there is a table called "test"
$sql = 'select * from test'

$db = New-Object -ComObject ADODB.Connection
$db.Open($connectionString)
$rs = $db.Execute($sql)

$results = While ($rs.EOF -eq $false)
{
    $CustomObject = New-Object -TypeName PSObject
    $rs.Fields | ForEach-Object -Process {
        $CustomObject | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Value
    }
    $CustomObject
    $rs.MoveNext()
}
$results | Out-GridView

Twitter This Tip! ReTweet this Tip!

Tuesday, July 21, 2015
Posted by AsifSaif

Facebook Group Integration

posts will be shared with facebook group in real time...
Monday, July 20, 2015
Posted by AsifSaif

No Picture

Content here

.
..
..
.
.
.
.
Until here,,,
Posted by AsifSaif

Getting SQL Server Connection String

If you’d like to contact an SQL Server database via PowerShell, you need a connection string. The connection string contains all pieces of information needed to contact the SQL server instance.

Traditionally, it is not trivial to construct such a connection string correctly. Here is a piece of code that defines a new function called Get-ConnectionString that helps you do this:

#requires -Version 2
function Get-ConnectionString
{ 
    $Path = Join-Path -Path $env:TEMP -ChildPath 'dummy.udl'
  
    $null = New-Item -Path $Path -ItemType File -Force
  
    $CommandArg = """$env:CommonProgramFiles\System\OLE DB\oledb32.dll"",OpenDSLFile "  + $Path 

    Start-Process -FilePath Rundll32.exe -ArgumentList $CommandArg -Wait
    $ConnectionString = Get-Content -Path $Path | Select-Object -Last 1
    $ConnectionString | clip.exe
    Write-Warning -Message 'Connection String is also available from clipboard'
    $ConnectionString
}

When you run Get-ConnectionString, PowerShell opens a dialog, and you can submit and test the connection details. Once you close the dialog window, PowerShell returns the connection string you just created with the help of the UI dialog.

Twitter This Tip! ReTweet this Tip!

Posted by AsifSaif

Recent Certifications

Popular Post

Recent Tweets

(c) 2011 - Asif R. Saif. Powered by Blogger.

- Copyright © Asif Saif -