我有一个字符串中的路径,
"C:\ TEMP\mybackup.zip"
我想在该脚本中插入一个时间戳,例如,
"C:\ temp\mybackup 2009-12-23.zip"
在PowerShell中有一种简单的方法吗?
Kei*_*ill 165
您可以使用子表达式在双引号字符串中插入任意PowerShell脚本代码,例如$(),如下所示:
"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"
Run Code Online (Sandbox Code Playgroud)
如果你从其他地方获得路径 - 已经是一个字符串:
$dirName = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext = [io.path]::GetExtension($path)
$newPath = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"
Run Code Online (Sandbox Code Playgroud)
如果路径恰好来自Get-ChildItem的输出:
Get-ChildItem *.zip | Foreach {
"$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}
Run Code Online (Sandbox Code Playgroud)
Tom*_*zel 12
这是一些应该工作的PowerShell代码.您可以将大部分内容组合成更少的行,但我希望保持清晰可读.
[string]$filePath = "C:\tempFile.zip";
[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
Move-Item -LiteralPath $filePath -Destination $newFilePath;
Run Code Online (Sandbox Code Playgroud)
小智 9
我需要导出我们的安全日志,并希望在协调世界时的日期和时间.这被证明是一个挑战,但执行起来非常简单:
wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddThhmmssZ")).evtx
Run Code Online (Sandbox Code Playgroud)
神奇的代码只是这一部分:
$(((get-date).ToUniversalTime()).ToString("yyyyMMddThhmmssZ"))
Run Code Online (Sandbox Code Playgroud)
小智 7
感谢上面的脚本。稍作修改即可添加正确结尾的文件。尝试这个 ...
$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**
Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
242842 次 |
| 最近记录: |