Combine path, file strings and literals for path

前端 未结 1 752
心在旅途
心在旅途 2021-01-26 07:08

Trying to combine a path, filename, and add some text along with a variable for Out-File log.

I\'ve tried many alternatives unsuccessfully and need assistan

相关标签:
1条回答
  • 2021-01-26 07:30

    Use the format operator (-f) for constructing the filename and Join-Path for building the path.

    $oldpath   = 'C:\Temp\TestFile.txt'
    
    $basename  = [IO.Path]::GetFileNameWithoutExtension($oldpath)
    $extension = [IO.Path]::GetExtension($oldpath)
    
    $filename  = '{0}_{1:yyyy-MM-dd HH:mm:ss}_Error{2}' -f $basename, (Get-Date), $extension
    
    $newpath   = Join-Path ([IO.Path]::GetDirectoryName($oldpath)) $filename
    

    Unless you must have the space in the date format you could simplify the format string by using the standard sortable format specifier (s) that will produce date strings like 2017-08-24T23:58:25 instead of 2017-08-24 23:58:25.

    $filename  = '{0}_{1:s}_Error{2}' -f $basename, (Get-Date), $extension
    

    If you want to construct the path as a string with inline variables you need to make sure that the underscores in your file name are kept separate from the variable name. Because underscores are valid name components for variable names $var_ is the variable var_, not the variable var followed by a literal underscore. Use curly braces to ensure that variables and literal underscores don't get mixed up.

    $oldpath   = 'C:\Temp\TestFile.txt'
    
    $date      = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
    $dirname   = [IO.Path]::GetDirectoryName($oldpath)
    $basename  = [IO.Path]::GetFileNameWithoutExtension($oldpath)
    $extension = [IO.Path]::GetExtension($oldpath)
    
    $newpath   = "${dirname}\${basename}_${date}_Error${extension}"
    

    Addendum: Your file names should not contain colons. Colons in Windows paths either terminate a drive name or separate the file name from the name of an alternate data stream. Your date format string should rather be something like yyyy-MM-dd HH-mm-ss or yyyy-MM-dd_HH-mm-ss to avoid this pitfall.

    0 讨论(0)
提交回复
热议问题