我.txt在一個檔案夾中有一個檔案串列,其命名如下:firstname[dot]lastname[underscore]nationality[underscore]date.txt
例子:
charles.pearson_FR_08-11-2021.txt
lena.smith_GB_11-12-2019.txt
paul.miller_XX_08-03-2017.txt
我想用來自查找表的國籍替換具有“XX”國籍的檔案的檔案名。
到目前為止我已經嘗試過:
$sqlcn = New-Object System.Data.SqlClient.SqlConnection
$sqlcn.ConnectionString = "MyData; MyCatalog;"
$sqlcn.Open()
$sqlcmd = $sqlcn.CreateCommand()
$query = "select username, nationality from mytable"
$sqlcmd.CommandText = $query
$adp = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcmd
$data = New-Object System.Data.DataSet
$adp.Fill($data) | Out-Null
# create a lookup Hashtable
$lookup = @{}
# build up the $lookup hash
foreach ($item in $data.Tables) {
$lookup[$item.username] = $item.nationality
}
[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'Desktop\testFolder'
[string[]]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*_XX_*.txt' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
#get the filename without the directory
[string]$newName = Split-Path -Path $_ -Leaf
#NEEDED: Lookup on the hashtable and rename the file
}
它正確列出了名稱中的所有.txt檔案,_XX_但我錯過了對哈希表的查找和重命名。
有關資訊,$data如下所示:
username nationality
-------- -----------
lena.jeankins
paul.mirabel GB
mickael.mudik GB
paul.miller FR
...
uj5u.com熱心網友回復:
您可以在這里做的不僅僅是選擇檔案 FullName,而是保留完整的 FileInfo 物件并使用.BaseName和.Extensions屬性,如下所示:
$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'Desktop\testFolder'
(Get-ChildItem -Path $rootPathForFiles -Filter '*.*_XX_*.txt' -File) | ForEach-Object {
$userName,$nationality,$date = $_.BaseName -split '_'
if ($lookup.ContainsKey($userName)) {
$newName = '{0}_{1}_{2}{3}' -f $userName, $lookup[$username], $date, $_.Extension
$_ | Rename-Item -NewName $newName
}
else {
Write-Warning "Could not retrieve nationality for user $userName"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/530774.html
標籤:电源外壳抬头
