Is there an option that mkdir does not return an object for the duration of an interactive PowerShell session?

1

mkdir in PowerShell returns the created directory which gets printed by default. When in an interactive PowerShell session, I get slightly disturbed by that default. Of course, I can turn the printing off by redirecting the output to $null:

mkdir $env:temp\foo > $null

Since I'd rather not write the redirection every time when I create a directory, I am wondering if there is an option that I can set to prevent the cmdlet from returning the object during an interactive PowerShell session.

René Nyffenegger

Posted 2019-10-24T18:32:25.093

Reputation: 1 862

Answers

1

Since mkdir is a function that wraps around New-Item, you can edit the function by getting it from the function PSProvider, change it and save it.

This command shows you what gets executed when you run mkdir:

Get-Item function:mkdir | Select-Object -ExpandProperty ScriptBlock

You can then actually change the scriptblock and save it again.

The Line that wraps mkdir around New-Item is this one:

$scriptCmd = {& $wrappedCmd -Type Directory @PSBoundParameters }

so we can just add a | Out-Null to that and it does the magic. All other output suppression methods like:

  • null =
  • > null
  • [void]

don't work in this case, because Microsoft worked with a steppablePipeline when creating this function.

this leaves us with this code:

function Set-Mkdir {

    [string]$Mkdir = Get-Item function:mkdir | Select-Object -ExpandProperty ScriptBlock

    $NewMkdir = $Mkdir.Replace('$scriptCmd = {& $wrappedCmd -Type Directory @PSBoundParameters }','$scriptCmd = {& $wrappedCmd -Type Directory @PSBoundParameters | Out-Null }')
    $NewMkdir = [ScriptBlock]::Create($NewMkdir)

    Set-item -Path function:mkdir -Value $NewMkdir

}

I put it in a function for you to put it in your PowerShell Profile, because this method does not persist when you close and reopen PowerShell. If you put it into your profile, you can run it in your interactive PowerShell session when you need to.

You could Alias these functions in your Profile and only run them if you really need to, like:

Set-Alias smkdir -Value Set-Mkdir
Set-Alias rmkdir -Value Restore-Mkdir

Edit:

If you want to restore the "old" mkdir you just need to switch the .Replace() Arguments and run it again, here's another function for that:

function Restore-Mkdir {

    [string]$Mkdir = Get-Item function:mkdir | Select-Object -ExpandProperty ScriptBlock

    $NewMkdir = $Mkdir.Replace('$scriptCmd = {& $wrappedCmd -Type Directory @PSBoundParameters | Out-Null }','$scriptCmd = {& $wrappedCmd -Type Directory @PSBoundParameters }')
    $NewMkdir = [ScriptBlock]::Create($NewMkdir)

    Set-item -Path function:mkdir -Value $NewMkdir

}

SimonS

Posted 2019-10-24T18:32:25.093

Reputation: 4 566