如何使用 Where-Object 和 StartsWith 根据内容过滤掉文件 - Powershell v4.0
How to use Where-Object and StartsWith to filter out files based on contents - Powershell v4.0
我正在尝试处理文件夹中的 SQL 个文件,重命名它们,如果文件内容以“/**”开头,那么我想从文件内容中删除前三行并覆盖文件。
下面的代码有效,但在添加注释掉的行之一时,它会显示 returns 错误消息。
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$sqlfolder = Get-ScriptDirectory
$files = Get-ChildItem $sqlfolder\* -Include *.sql
Foreach ($file in $files) {
Write-Output $file.name
$newName = $file.name.Substring($file.name.LastIndexOf(" ")+1)
Rename-Item $file -NewName $newName
get-content $file |
##Where-Object {$_.StartsWith("/**")} |
##Where-Object {$_ -Like "/**"} |
select -Skip 3 |
set-content "$file-temp"
move "$file-temp" $file -Force
}
我想要注释掉的行之一以确保前三行只会从以字符串“/**”开头的文件中删除。
错误信息:
move : Cannot find path ...-temp' because it does not exist.
... ObjectNotFound ... PathNotFound ...
我只能按照评论中的建议使用 If
修改以文本“/**”开头的文件。这是最终代码:
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$sqlfolder = Get-ScriptDirectory
$files = Get-ChildItem $sqlfolder\* -Include *.sql
Foreach ($file in $files) {
# Write-Output $file.name
$newName = $file.name.Substring($file.name.LastIndexOf(" ")+1)
Rename-Item $file -NewName $newName
$firstLine = (Get-Content $file)[0]
if ($firstLine.StartsWith("/**")){
Get-Content $file |
select -Skip 3 |
set-content "${file}-temp"
move "${file}-temp" $file -Force
}
}
我正在尝试处理文件夹中的 SQL 个文件,重命名它们,如果文件内容以“/**”开头,那么我想从文件内容中删除前三行并覆盖文件。 下面的代码有效,但在添加注释掉的行之一时,它会显示 returns 错误消息。
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$sqlfolder = Get-ScriptDirectory
$files = Get-ChildItem $sqlfolder\* -Include *.sql
Foreach ($file in $files) {
Write-Output $file.name
$newName = $file.name.Substring($file.name.LastIndexOf(" ")+1)
Rename-Item $file -NewName $newName
get-content $file |
##Where-Object {$_.StartsWith("/**")} |
##Where-Object {$_ -Like "/**"} |
select -Skip 3 |
set-content "$file-temp"
move "$file-temp" $file -Force
}
我想要注释掉的行之一以确保前三行只会从以字符串“/**”开头的文件中删除。
错误信息:
move : Cannot find path ...-temp' because it does not exist.
... ObjectNotFound ... PathNotFound ...
我只能按照评论中的建议使用 If
修改以文本“/**”开头的文件。这是最终代码:
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$sqlfolder = Get-ScriptDirectory
$files = Get-ChildItem $sqlfolder\* -Include *.sql
Foreach ($file in $files) {
# Write-Output $file.name
$newName = $file.name.Substring($file.name.LastIndexOf(" ")+1)
Rename-Item $file -NewName $newName
$firstLine = (Get-Content $file)[0]
if ($firstLine.StartsWith("/**")){
Get-Content $file |
select -Skip 3 |
set-content "${file}-temp"
move "${file}-temp" $file -Force
}
}