Skip to main content

Snippets

Logged in users

$loggedInUsers = (query user) -split "\n" -replace '\s\s+', ';' | convertfrom-csv -Delimiter ';'
# example output

PS C:\> $loggedInUsers | Format-Table

USERNAME SESSIONNAME ID STATE  IDLE TIME LOGON TIME
-------- ----------- -- -----  --------- ----------
joebob   console     15 Active 6:09      1/12/1979 3:33 AM

PS C:\> $loggedInUsers.USERNAME
joebob

IPv6 to MAC address

$ipv6Address = "fe80::9657:a5ff:fe17:aeac"

# First attempt - shows all entries
Get-NetNeighbor -AddressFamily IPv6 | Where-Object {$_.IPAddress -eq "$($ipv6Address)"}

# Second attempt - only show Permananet entries
Get-NetNeighbor -AddressFamily IPv6 | Where-Object {($_.State -eq 'Permanent') -And ($_.IPAddress -eq "$($ipv6Address)")}

# Show just the Windows MAC address format with dashes
(Get-NetNeighbor -AddressFamily IPv6 | Where-Object {($_.State -eq 'Permanent') -And ($_.IPAddress -eq "$($ipv6Address)")}).LinkLayerAddress

# Normal format with colons
(Get-NetNeighbor -AddressFamily IPv6 | Where-Object {($_.State -eq 'Permanent') -And ($_.IPAddress -eq "$($ipv6Address)")}).LinkLayerAddress -replace '-', ':'

 

While a file exists or not

# while a file exists
While (Test-Path C:\Temp\File_I_Want_Gone.txt -ErrorAction SilentlyContinue) {
  # Do something here while the file exists
}
# while a file doesn't exists
While (!(Test-Path C:\Temp\File_I_Want_Gone.txt -ErrorAction SilentlyContinue)) {
  # Do something here while the file doesn't exists
}
# while a file exists
While (Test-Path C:\Temp\File_I_Want_Gone.txt -ErrorAction SilentlyContinue) {
  # try to delete the file, continue silently if we can't
  Remove-Item "C:\Temp\File_I_Want_Gone.txt" -ErrorAction SilentlyContinue
  # print date each time just to give some sort of feedback on the console
  Get-Date
}

Testing Microsoft SQL database connectivity

function Test-SQLConnection
{    
    [OutputType([bool])]
    Param
    (
        [Parameter(Mandatory=$true,
                    ValueFromPipelineByPropertyName=$true,
                    Position=0)]
        $ConnectionString
    )
    try
    {
        $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString;
        $sqlConnection.Open();
        $sqlConnection.Close();

        return $true;
    }
    catch
    {
        return $false;
    }
}
Test-SQLConnection "Data Source=localhost;database=someDatabase;User ID=bogusTestUser;Password=bogusTestPassword;"

[Source]