Solved

Help creating a log with Powershell

Posted on 2014-07-28
6
236 Views
Last Modified: 2014-07-29
Hello Powershell experts,

I have the following code to move all the files in a folder called source to a different folder called target:

Get-ChildItem -Path "c:\source"  | select name | Move-Item -Destination "c:\target"

This works as expected.  Now I would like the name of each file moved written to a text file.  I'm not sure how to do this.  My initial thought was something like:

Get-ChildItem -Path "c:\source"  | select name | Move-Item -Destination "c:\target" | foreach-object {write-host "$_.name moved successfully" >> c:\movereport.txt}

This didn't work.  How would I accomplish this?

Thanks,
Nick
0
Comment
Question by:ndalmolin_13
  • 2
  • 2
  • 2
6 Comments
 
LVL 28

Expert Comment

by:becraig
Comment Utility
Get-ChildItem -Path "c:\source"  | select fullname | % {
$filer = $_
try {
Move-Item $filer -Destination  "c:\target"
"$filer move was successful" | c:\success.log
}
catch {
"$filer  was not moved" | c:\failure.log
}

Open in new window

}
0
 
LVL 82

Accepted Solution

by:
oBdA earned 500 total points
Comment Utility
There were several issues with your command.
* When you're inside a string and you want to access an object's property (as in "$_.Name moved ..."), you need to use "$($_.Name) moved ...", otherwise the parser will evaluate that to "$_" and the string ".Name moved ....".
* "Write-Host", as its name implies, sends the pipeline output to the Powershell host (that is, the console), and that's where the output stops. Output sent to Write-Host will not be passed further down the pipeline. Just pass the string, or if you want to be explicit about sending it down the pipeline, pipe it to "Write-Output".
Get-ChildItem -Path "C:\Source" | ForEach-Object {
	Move-Item $_.FullName -Destination "C:\Target" -ErrorAction SilentlyContinue
	If ($?) {
		$Result = "Success"
		$Color = [ConsoleColor]::Green
	} Else {
		$Result = "Error"
		$Color = [ConsoleColor]::Red
	}
	"$($_.Name): $($Result)" | Write-Host -ForegroundColor $Color
	"$($_.Name): $($Result)" >> c:\movereport.txt
}

Open in new window

Or instead of using the redirection, you can use Add-Content with -PassThru instead of lines 10 and 11:
"$($_.Name): $($Result)" | Add-Content -Path "c:\movereport.txt" -PassThru | Write-Host -ForegroundColor $Color

Open in new window

Powershell 3.0 and later has the "Tee-Object" cmdlet that can send pipeline output to file and then pass it further down the pipeline; with that, you could use this instead of lines 10 and 11:
"$($_.Name): $($Result)" | Tee-Object -FilePath "c:\movereport.txt" -Append | Write-Host -ForegroundColor $Color

Open in new window


becraig,
Move-Item doesn't throw an exception when it can't move a file, it just errors out. You either need to check $?, or use -ErrorAction Stop.
0
 
LVL 28

Expert Comment

by:becraig
Comment Utility
Thanks I was actually planning to rewrite with an error.clear at the start of each move and then use if/else to check error condition after the move writing the exception to the log.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:ndalmolin_13
Comment Utility
What is the "$?" ?
0
 
LVL 82

Expert Comment

by:oBdA
Comment Utility
That's a (boolean) default variable that is $True if the last cmdlet executed without error, $False otherwise.
Get-Item $ENV:SystemRoot | Out-Null; "Got a known item; expected result is True: " + $?
Get-Item ".\asd.fgh" -ea si; "Created an error; expected result is False: " + $?

Open in new window

0
 
LVL 1

Author Closing Comment

by:ndalmolin_13
Comment Utility
Thanks for the help
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

This script checks a path to see if a folder exists. If the folder does exist you will get output "The folder has previously been created. No action taken" If not it will create the folder. Then adds one user modify permission to the folder. It …
This is a PowerShell web interface I use to manage some task as a network administrator. Clicking an action button on the left frame will display a form in the middle frame to input some data in textboxes, process this data in PowerShell and display…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now