2

我有这个重命名文件的 PowerShell 脚本。以下是字符串操作代码的一部分(不是我的实际代码,只是为了说明问题):

$text="String1.txt"
$text
$text.trimend(".txt")
$date=Get-Date -format yyyyMMdd
$text + $date
$newFile = $text.trimend(".txt") + "_" + $date + ".bak"
$newFile
$NewFile1 = $newFile.TrimEnd("_$date.bak") + ".bak"
$NewFile1

结果是:

String1.txt
String1
String1.txt20131104
String1_20131104.bak
String.bak

为什么1末尾的 也String1被删除了?我期待的结果是String1.bak

4

2 回答 2

5

trimend() 方法接受一个字符数组(不是字符串)参数,并将修剪数组中出现在字符串末尾的所有字符。

我通常使用 -replace 运算符来修剪字符串值:

$text="String1.txt"
$text 
$text = $text -replace '\.txt$',''
$text

String1.txt
String1
于 2013-11-04T01:37:10.807 回答
0

在PowerShell 上开发从字符串中删除文本的答案,我正在使用这些正则表达式来修剪未知类型的扩展名,并可能.在文件名的其他位置:

$imagefile="hi.there.jpg"
$imagefile
hi.there.jpg
$imagefile -replace '\.([^.]*)$', ''
hi.there
$imagefile -replace '([^.]*)$', ''
hi.there.
于 2016-08-09T07:49:14.493 回答