I'm slowly getting to grips with Powershell but I cant see how to capture the for-each loop in a log (its probably something straight forward). My current code creates the log but doesnt seem to write to it - any ideas where I am going wrong?
$CSVImp = Import-Csv -Path "C:\Support\Powershell-Rename\Data.csv"
$OutputLog = ".\output.log"
Write $CSVImp | Where-Object { $_.CompName -eq $env:computername } | ForEach-Object {Rename-Item $_.FileLocation -NewName $_.FileRename -ErrorAction SilentlyContinue } | Out-File $OutputLog -Append
Thanks
CodePudding user response:
The scriptblock you pass to ForEach-Object
can have as many statements as you like:
... |ForEach-Object {
Rename-Item $_.FileLocation -NewName $_.FileRename -ErrorAction SilentlyContinue
if($?){
"[ ] Successfully renamed '$($_.FileLocation)' to '$($_.FileRename)'"
}
else {
"[!] Failed to rename '$($_.FileLocation)' to '$($_.FileRename)'"
}
} |Out-File $OutputLog -Append
CodePudding user response:
I'd suggest something like this where you use a Try/Catch block to log your entries.
$CSVImp = Import-Csv -Path "C:\Support\Powershell-Rename\Data.csv"
$OutputLog = ".\output.log"
$CSVImp | Where-Object { $_.CompName -eq $env:computername } |
ForEach-Object {
Try {
Rename-Item $_.FileLocation -NewName $_.FileRename -ErrorAction Stop
"Success: Rename $($_.FileLocation) to $($_.FileRename)" |
Out-File $OutputLog -Append
}
Catch {
"Failed: Renamed $($_.FileLocation) to $($_.FileRename)" |
Out-File $OutputLog -Append
}
Note: Untested code!