2017-01-01 46 views
0

我有一个powershell脚本,它可以在将文件从dev复制到根文件夹后更改文件扩展名等。我已经成功复制了这些文件。然而,我坚持使用适用于所有子文件夹(我想排除开发文件夹)的-Recurse或仅将代码应用于eoot文件夹。Powershell -Recurse参数;如何排除特定的子目录

CODE:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "$w = $args[0];foreach ($file in Get-ChildItem -Recurse -Path "$w" -Exclude *.bat, *.txt, *.png, *.jpg, *.jpeg, *.gif, *.mp3, *.mp4, dev\\*) {"$w+$file";(Get-Content $w$file).replace('dev/', '') | Set-Content "$w$file";(Get-Content $w$file).replace('.min.js', '.minjs') | Set-Content "$w$file";(Get-Content $w$file).replace('.json', '.xson') | Set-Content "$w$file";(Get-Content $w$file).replace('https://www.google-analytics.com/analytics.js', '/httpswgacanalyticsjs/') | Set-Content "$w$file";(Get-Content $w$file).replace('.js', '.min.js') | Set-Content "$w$file";(Get-Content $w$file).replace('.minjs', '.min.js') | Set-Content "$w$file";(Get-Content $w$file).replace('.xson', '.json') | Set-Content "$w$file";(Get-Content $w$file).replace('/httpswgacanalyticsjs/', 'https://www.google-analytics.com/analytics.js') | Set-Content "$w$file";(Get-Content $w$file).replace('.min.css', '.mincss') | Set-Content "$w$file";(Get-Content $w$file).replace('.css', '.min.css') | Set-Content "$w$file";(Get-Content $w$file).replace('.mincss', '.min.css') | Set-Content "$w$file";};Write-Host ".""" "%path%" 

输入:

FOLDER 
    -> dev 
     ->files 
     ->folders 

OUTPUT:

FOLDER 
    -> dev  //exclude 
     ->files //exclude 
     ->folders //exclude 
    ->files //execute code on this 
     ->folders //execute code on this 

回答

0

尝试这样的事情(PowerShell的V5使用-file选项)

$w = "c:\temp\"; 
[email protected]("*.bat", "*.txt", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.mp3", "*.mp4") 

$hashreplace = @{} 
$hashreplace.'dev/'= '' 
$hashreplace.'.min.js'= '.minjs' 
$hashreplace.'.json'= '.xson' 
$hashreplace.'https://www.google-analytics.com/analytics.js'= '/httpswgacanalyticsjs/' 
$hashreplace.'.js'= '.min.js' 
$hashreplace.'.minjs'= '.min.js' 
$hashreplace.'.xson'= '.json' 
$hashreplace.'/httpswgacanalyticsjs/'= 'https://www.google-analytics.com/analytics.js' 
$hashreplace.'.min.css'= '.mincss' 
$hashreplace.'.css'= '.min.css' 
$hashreplace.'.mincss'= '.min.css' 

foreach ($file in Get-ChildItem -Recurse -File -Path "$w" -Exclude $exclude | where {$_.fullname -notlike "*\dev\*"}) 
{ 
    $text=(Get-Content $file.FullName) 
    $hashreplace.Keys | %{ $text = $text.Replace($_, $hashreplace[$_])} 
    $text | set-content $file.FullName 
}; 
+0

将如何我从批处理文件启动这个Powershell文件?我看不到它能够工作,因为它们是路径中的空间。另外我如何输入一个参数? –

+0

powershell -executionPolicy bypass -noexit -file“c:\ temp \ path with space \ test.ps1”“argument” – Esperento57

+0

经过多次试验和错误之后,where语句在这里缺少星号“* \ dev \ *”。感谢您的帮助,它现在正在运行。 –

0

我没有测试过这个,所以我只打算关闭理论但是下面可能帮助从我了解你正在尝试做的事情。

添加在类似:

$filesToRecurse = Get-ChildItem -Path {pathToFileToRecurse} -Exclude {pathToFolderToExclude} | where {! $_.PSIsContainer} 

然后使用$ filesToRecurse变量的文件列表进行重命名,因为它不会包含要排除的文件或文件夹。

注意:您还可以创建,如果要排除多个位置使用数组变量等