Skip to content

Instantly share code, notes, and snippets.

@powercode
Created March 17, 2017 19:40
Show Gist options
  • Save powercode/8bc93f8df69ed969e4ba89743b4b46d9 to your computer and use it in GitHub Desktop.
Save powercode/8bc93f8df69ed969e4ba89743b4b46d9 to your computer and use it in GitHub Desktop.
Touch in PowerShell
using namespace System.Management.Automation
function Update-LastWriteTime {
[CmdletBinding(DefaultParameterSetName='Path', SupportsShouldProcess)]
[OutputType([IO.FileInfo])]
[Alias('touch')]
param(
[Parameter(Mandatory, ParameterSetName="Path", Position=0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]] $Path,
[Alias('PSPath')]
[Parameter(Mandatory, ParameterSetName="LiteralPath", ValueFromPipelineByPropertyName)]
[string[]] $LiteralPath,
[switch] $Quiet
)
begin{
class Toucher {
[PathIntrinsics] $PathHelper
[DateTime] $Now
Toucher([PathIntrinsics] $pathHelper) {
$this.PathHelper = $pathHelper
$this.Now = [DateTime]::Now
}
[object] ResolveLiteralPath([string] $path) {
$provider = $null
$drive = $null
$unresolved = $this.PathHelper.GetUnresolvedProviderPathFromPSPath($Path, [ref]$provider, [ref] $drive)
if($provider.ImplementingType -ne [Microsoft.PowerShell.Commands.FileSystemProvider]) {
return [Toucher]::GetErrorRecordForPath($path)
}
else {
return $unresolved
}
}
[object] ResolvePath([string] $path) {
$provider = $null
try {
$resolved = $this.PathHelper.GetResolvedProviderPathFromPSPath($Path, [ref]$provider)
if($provider.ImplementingType -ne [Microsoft.PowerShell.Commands.FileSystemProvider]) {
return [Toucher]::GetErrorRecordForPath($path)
}
else {
return $resolved
}
}
catch [ItemNotFoundException] {
return @($this.ResolveLiteralPath($path))
}
}
[IO.FileInfo] Touch([string] $path) {
if (![IO.File]::Exists($path)) {
[IO.File]::Create($path)
}
else {
[IO.File]::SetLastWriteTime($path, $this.Now)
}
return [IO.FileInfo]::new($path)
}
static [ErrorRecord] GetErrorRecordForPath([string] $path) {
$ex = [ArgumentException]::new("touch is only supported for paths in the file system")
return [ErrorRecord]::new($ex, "", [ErrorCategory]::InvalidArgument, $path)
}
}
$toucher = [Toucher]::new($pscmdlet.SessionState.Path)
}
process {
if ($PSCmdlet.ParameterSetName -eq 'Path') {
foreach($p in $Path) {
$res = $toucher.ResolvePath($p)
if ($res -is [ErrorRecord]) {
$pscmdlet.WriteError($res)
}
else {
foreach($r in $res) {
if ($pscmdlet.ShouldProcess($r, "touch")) {
$fi = $toucher.Touch($r)
if (!$Quiet) {
$pscmdlet.WriteObject($fi, $false)
}
}
}
}
}
}
else {
foreach($p in $LiteralPath) {
$res = $toucher.ResolveLiteralPath($p)
if ($res -is [ErrorRecord]) {
$pscmdlet.WriteError($res)
}
else {
if ($pscmdlet.ShouldProcess($res, "touch")) {
$fi = $toucher.Touch($res)
if (!$Quiet) {
$pscmdlet.WriteObject($fi, $false)
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment