Try / Catch


hi all, 

i have used in past not having success time. in below failures.txt file created blank...

backuptarget = "\\server\share"  $todaysdate = $((get-date).tostring('dd-mm-yyyy'))  import-module activedirectory    # list of print servers backed  $servers = get-adcomputer -filter * -searchbase "ou=printservers,dc=dev,dc=local"    foreach ( $server in $servers ) {   	# capture server name use error reporting  	$catchhostname = $server.name  	try {  		# servers hostname , store variable  		$hostname = $server.name  		# see if server has backup. if rename previous backup  		if (test-path -path $backuptarget\$hostname.printerexport) {  			rename-item "$backuptarget\$hostname.printerexport" "$backuptarget\$hostname.printerexportold"  		}  		# perform backup  		invoke-expression 'c:\windows\system32\spool\tools\printbrm.exe -s \\$hostname -b -o force -f "$backuptarget\$hostname.printerexport"'  		# check see if new backup file exists, if delete older backup  		if (test-path -path $backuptarget\$hostname.printerexport) {  		remove-item "$backuptarget\$hostname.printerexportold"  		}  	}  	catch {  		$failedservers += "$catchhostname @ $todaysdate"  	}  	$failedservers | out-file "$backuptarget\failures.txt" -append  }

if move out-file command catch section no failures.txt file being created @ all.

i trying generate list of servers have failed export printer configuration.

thanks.

my apologies, neglected see invoke-expression , referencing executable. best bet leverage $lastexitcode vs. try/catch to handle windows apps. (see about_automatic_variables more information this).

something work:

invoke-expression 'c:\windows\system32\spool\tools\printbrm.exe -s \\$hostname -b -o force -f "$backuptarget\$hostname.printerexport"' # check see if new backup file exists, if delete older backup if ($lastexitcode -ne 0) {     #assume failed , log    "$catchhostname @ $todaysdate" | out-file "$backuptarget\failures.txt" -append } if (test-path -path $backuptarget\$hostname.printerexport) {     remove-item "$backuptarget\$hostname.printerexportold" }


boe prox
blog | twitter
poshwsus | poshpaig | poshchat | posheventui
powershell deep dives book



Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

Motherboard replacement

Cannot create Full Text Search catalog after upgrading to V12 - Database is not fully started up or it is not in an ONLINE state

Remote Desktop App - Error 0x207 or 0x607