powershell实现修改文件的创建时间以及最后更新时间

170
补充展位 Pages_Weblog_Get#0
文章摘要
此内容由人工摘要内容,并由AI根据文章内容进行润色
通过PowerShell脚本修改文件创建时间和最后更新时间的方法:添加System.Management.Automation引用,使用Set-ItemProperty命令设置LastWriteTime和CreationTime属性,提供C#调用示例,适用于需要调整文件时间戳的场景。

powershell实现修改文件的创建时间以及最后更新时间

接到一个需求:

要用最新的程序重新打包一份以前的项目安装程序 但要求把程序包内的文件的创建时间修改为以前的一个时间点 据说是为了应付上面审查 大概意思是相关人员检查时防止被查到文件时间太新,虽然觉得有点欲盖弥彰的意思 但毕竟是工作 以下是实现修改的文件创建时间以及最后更新时间的 方法

需要先添加powershell链接库引用

首先引用 System.Management.Automation

应该是在C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0目录下

///运行脚本封装方法
private static string RunScript(string scriptText)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);
            pipeline.Commands.Add("Out-String");
            Collection<PSObject> results = pipeline.Invoke();
            runspace.Close();
            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            return stringBuilder.ToString();
}

测试调用修改更新时间例子

//修改文件最后更新时间
string cmd = $"Set-ItemProperty -Path {file.FullName} -Name LastWriteTime -Value \"2020-12-15 11:33:44\"";
string xx= RunScript(cmd);

//修改文件创建时间
cmd = $"Set-ItemProperty -Path {file.FullName} -Name CreationTime -Value \"2020-12-15 11:33:44\"";
xx = RunScript(cmd);
补充展位
Pages_Weblog_Get#cd127053-cdde-4f21-b3e2-adf700e1145a
补充展位 Pages_Weblog_Get#1
补充展位 Pages_Weblog_Get#2
专题推荐
暂无内容
补充展位 Pages_Weblog_Get#3