Reputation: 33
Long day, might be missing something obvious, but the nested IF statements below should work. Any suggestions?
Basically, what I am trying to do:
I did the below:
$Computer = "hostName"
Enter-PSSession -ComputerName $($Computer)
$LogFileName = "program_" + $Computer + ".log"
$LogFilePath = "\\$Computer\C$\users\$env:USERNAME\desktop\$LogFileName"
$DestPath = "\\$Computer\C$\users\$env:USERNAME\ProgramTest\"
$LogCopy = "programCopy_" + $Computer + ".log"
IF(Test-Path $($DestPath)){
If(Test-Path "$DestPath\$LogCopy"){
Remove-Item "$DestPath\$LogCopy"
Copy-Item $($LogFilePath) $($DestPath)
}
Else{
Copy-Item $($LogFilePath) $($DestPath)
}
ELSE{
New-Item -ItemType directory -Path $($DestPath)
Copy-Item $($LogFilePath) $($DestPath)
}
}
Upvotes: 0
Views: 359
Reputation: 46730
I see you have already accepted an answer but I wanted to offer and improvement on the logic. The nested if's, while do work, have some redundancies in them. Assuming I understand your intention...
# If the folder does not exist create it. If it does move on
If(!(Test-Path $DestPath)){New-Item -ItemType directory -Path $DestPath}
# If the log file already exists. Remove It.
If(Test-Path "$DestPath\$LogCopy"){Remove-Item "$DestPath\$LogCopy"}
# Regardless of what happens we are going to copy the file. No need to repeat the code.
Copy-Item $($LogFilePath) $($DestPath)
While that is an improvement on the logic we can take this a little further. If you want to be sure the file is fresh and overwritten Copy-Item
will handle that for you.
# If the folder does not exist create it. If it does move on
If(!(Test-Path $DestPath)){New-Item -ItemType directory -Path $DestPath}
# Regardless of what happens we are going to copy the file. No need to repeat the code.
Copy-Item $LogFilePath $DestPath -Confirm:$false -Force
$()
is the notation for a subexpression. A common use in similar context would be to ensure that a variable expands properly in a string. As shown in the following example
PS C:\Users\Cameron> $data = @{Matt="Awesome"}
PS C:\Users\Cameron> "$data.Matt"
System.Collections.Hashtable.Matt
PS C:\Users\Cameron> "$($data.Matt)"
Awesome
Currently in your code, while causing no harm, it is redundant.
Upvotes: 4
Reputation: 2244
Beyond the dubious use of $($Variable)
(completely redundant; just use $Variable
), you've misplaced a closing brace. The last five lines should look like this:
}
ELSE{
New-Item -ItemType directory -Path $($DestPath)
Copy-Item $($LogFilePath) $($DestPath)
}
If that doesn't work, let us know what's actually happening: errors and such when you try to run it.
Upvotes: 0