Skip to content

Instantly share code, notes, and snippets.

@SteveGilham
Created May 19, 2018 07:04
Show Gist options
  • Save SteveGilham/1a2bd6e12e9669ce21b7d15697331b52 to your computer and use it in GitHub Desktop.
Save SteveGilham/1a2bd6e12e9669ce21b7d15697331b52 to your computer and use it in GitHub Desktop.
a more complex cmdlet in C++/CLI -- source file
#include "TouchFileCommand.h"
namespace PSBook { namespace Commands
{
SetFileTouchTimeCommand::SetFileTouchTimeCommand(void)
{
Date = DateTime::Now;
rm = gcnew Resources::ResourceManager(L"PowershellCpp.Messages", GetType()->Assembly);
}
void SetFileTouchTimeCommand::ProcessRecord(void)
{
if (FileInfo != nullptr)
{
TouchFile(FileInfo);
}
ProviderInfo ^ provider = nullptr;
try
{
auto resolvedPaths = GetResolvedProviderPathFromPSPath(Path, provider);
for each (String ^ path in resolvedPaths)
{
if (File::Exists(path))
{
auto info = gcnew System::IO::FileInfo(path);
TouchFile(info);
}
else
{
HandleFileNotFound(path, nullptr);
return;
}
}
}
catch (ItemNotFoundException ^ nf)
{
HandleFileNotFound(Path, nf);
}
}
void SetFileTouchTimeCommand::HandleFileNotFound(String ^ path, Exception ^ exception)
{
auto message = String::Format(
System::Globalization::CultureInfo::CurrentCulture,
rm->GetString("FileNotFound"), path);
auto ae = gcnew ArgumentException(message, exception);
auto error = gcnew ErrorRecord(ae, "FileNotFound", ErrorCategory::ObjectNotFound, path);
WriteError(error);
}
void SetFileTouchTimeCommand::TouchFile(System::IO::FileInfo ^ fileInfo)
{
if(ShouldProcess(fileInfo->FullName, String::Format(
System::Globalization::CultureInfo::CurrentCulture,
rm->GetString("ConfirmString"), Date)))
{
try
{
fileInfo->LastWriteTime = Date;
}
catch (UnauthorizedAccessException ^ uae)
{
auto error = gcnew ErrorRecord(uae, "UnauthorizedFileAccess", ErrorCategory::PermissionDenied, fileInfo ->FullName);
auto detail = String::Format(
System::Globalization::CultureInfo::CurrentCulture,
rm->GetString("AccessDenied"),
fileInfo->FullName);
error->ErrorDetails = gcnew ErrorDetails(detail);
WriteError(error);
return;
}
WriteObject(fileInfo);
}
}
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment