使用 Out-File 在文件名中包含日期变量
Using Out-File to have a date variable within the name for the file
我正在尝试使用 Out-File 在文件名中包含一个日期变量。
但是,出现如下异常
$EndDate = get-date -UFormat "%Y-%m-%d %H:%M:%S"
Out-File -FilePath "C:\output$host-$EndDate.json
Out-File : The given path's format is not supported.
At E:\sample.ps1:442 char:69
+ ... MaxValue) | Out-File -FilePath "E:\output$serverHostName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], NotSupportedException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
而不是
Out-File -FilePath "C:\output$host-$EndDate.json"
$EndDate = get-date -UFormat "%Y-%m-%d %H:%M:%S"
$myFileName = 'C:\output\{0}-{1}.json' -f $host, ($EndDate.ToString() -replace ':','') -replace '\s',''
Out-File -filepath $myFileName
此外,如果您的目录不存在,您可能需要使用 New-Item command 而不是 Out-File。您的错误似乎表明创建文件时该目录可能不可用。
New-Item -path $myFileName -Force
正如 Bill Stewart 所指出的,$host
is a reserved word,因此请谨慎使用。
我正在尝试使用 Out-File 在文件名中包含一个日期变量。 但是,出现如下异常
$EndDate = get-date -UFormat "%Y-%m-%d %H:%M:%S"
Out-File -FilePath "C:\output$host-$EndDate.json
Out-File : The given path's format is not supported.
At E:\sample.ps1:442 char:69
+ ... MaxValue) | Out-File -FilePath "E:\output$serverHostName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], NotSupportedException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
而不是
Out-File -FilePath "C:\output$host-$EndDate.json"
$EndDate = get-date -UFormat "%Y-%m-%d %H:%M:%S"
$myFileName = 'C:\output\{0}-{1}.json' -f $host, ($EndDate.ToString() -replace ':','') -replace '\s',''
Out-File -filepath $myFileName
此外,如果您的目录不存在,您可能需要使用 New-Item command 而不是 Out-File。您的错误似乎表明创建文件时该目录可能不可用。
New-Item -path $myFileName -Force
正如 Bill Stewart 所指出的,$host
is a reserved word,因此请谨慎使用。