【发布时间】:2016-10-27 04:21:51
【问题描述】:
我正在尝试让我的 PS 脚本在目录中如下所示...
C:\FAKEENV
└───DEVbox
├───PRD
| └──BatFile.txt
└───STG
└──BatFile.txt
我想要做的是查看 .txt 在过去 12 小时内是否发生了变化。如果有,请将 bat 文件中的字符串从 STG 文件夹中的“dev”替换为“stg”,并将 PRD 文件夹中的“stg”替换为“”(无)。我已经改变了变量并操纵了我的代码几个小时,但没有运气。我知道我的逻辑是错误的,因为当我单步执行时,它永远不会到达将操纵 bat 文件的 if 语句。
Clear-Host
$date = Get-Date
$hours = '-12'
#$StgDestFile = 'C:\FakeEnv\DEVbox\STG'
#$PrdDestFile = 'C:\FakeEnv\DEVbox\PRD'
$dest_file = 'C:\FakeEnv\DEVbox'
foreach($file in (Get-ChildItem $dest_file -Recurse))
{
#Check for changes from last $hours
if($file.LastWriteTime -gt ($date).AddHours($hours))
{
if($file -eq 'STG')
{
(Get-Content $dest_file\STG\BatFile.txt) | Foreach-Object {
$_ -replace 'dev', 'stg' `
#Format: -replace 'SOMETHING', 'SOMETHING ELSE' `
} | Set-Content $dest_file
#Insert logic for uninstall and install of 'feature'
#Insert logic for confirmation message of changes
}
elseif($file -eq 'PRD')
{
(Get-Content $dest_file\PRD\BatFile.txt) | Foreach-Object {
$_ -replace 'dev', 'stg' `
#Format: -replace 'SOMETHING', 'SOMETHING ELSE' `
} | Set-Content $dest_file
#Insert logic for uninstall and install of 'feature'
#Insert logic for confirmation message of changes
}
}
}
#If no changes occurded, log that nothing happened
else
{
$LogDestination = 'C:\FakeEnv\Logs'
$LogPathExist = Test-Path "$LogDestination"
#Do this if folder does not exist
#If the folder has not already been created, create it and write to log file
if($LogPathExist -eq $false)
{
New-Item $LogDestination -ItemType directory
New-Item $LogDestination\log.log -ItemType file
Add-Content $LogDestination\log.log "Script detected no changes in $dest_file on $date"
}
#Do this is folder does exist
#if the folder exists, append to log file
else
{
Add-Content $LogDestination\log.log "`nScript detected no changes in $dest_file on $date"
}
}
【问题讨论】:
标签: powershell replace find