Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Friday, May 16, 2025

Touch in Powershell

Linux has Touch. I needed touch today in PowerShell. This is what I came up with. 

function touch {
    param (
        [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
        [string[]]$Paths
    )
    foreach ($Path in $Paths) {
        $dir = Split-Path $Path
        if (-not (Test-Path $dir)) {
            New-Item -ItemType Directory -Path $dir -Force | Out-Null
        }
        if (-not (Test-Path $Path)) {
            New-Item -ItemType File -Path $Path -Force | Out-Null
        }
    }
}

Add it to your PowerShell profile by pasting the function into your current PowerShell window then:

touch $PROFILE
notepad $PROFILE

Paste the function into the text file and save it. Then all future PowerShell sessions can use:

touch <path to your file>

One thing I built into it was to build out the intermediary folders in case they don't exist.

Thursday, January 9, 2025

Using SSH on Windows with Powershell

I've come to prefer CLIs over GUIs. Rather than install Putty (or grab the portal version and copy it to the server I want to use), I prefer to SSH directly from Powershell since Microsoft started including a client in the Windows Features.

First, make sure it's installed. From a Powershell prompt running with elevated privileges:

if (-not (Get-WindowsCapability -Online | Where-Object { $_.Name -like 'OpenSSH.Client*' -and $_.State -eq 'Installed' })) {
    Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
}
This will check if the SSH client is installed and if not, it will install it. 

Using SSH is pretty much the same as it is on Linux then:
ssh <username>@<hostname/fqdn/ip> -p <port>

However, if you do that, you'll be prompted for the password of the user. You could enable key based login, which would essentially use a huge alternate password stored in a file on your computer to connect to the target. 

First make sure your system has a key. If you already have keys, this will overwrite them, so use carefully. You can always change the name to something unique to make sure it doesn't get overwritten. Just update the name in the rest of the commands here. 
On Linux
ssh-keygen -f ~/.ssh/id_rsa -b 4096 -N ""

On Windows
ssh-keygen -f "$HOME\.ssh\id_rsa" -t rsa -b 4096 -N '""'

Then:

For Linux
ssh-copy-id -i ~/.ssh/id_rsa.pub -p 22 <username>@<hostname/fqdn/ip>

For Windows
type ~\.ssh\id_rsa.pub | ssh <username>@<hostname/fqdn/ip> "cat >> ~/.ssh/authorized_keys"

Now you should be able to SSH from Powershell using the same command above:
ssh <username>@<hostname/fqdn/ip> -p <port>
Except that now, the client in Powershell will attempt to pass your key to the target to authenticate with. Since you key contains a super-long alternate password, you will be logged in. One cool thing is that this survives password changes on the target account.