Solved

PowerShell Query Help

Posted on 2014-10-07
4
150 Views
Last Modified: 2014-10-07
I have the following code. The full script, amongst other things, imports data from various SQL scripts into a query that it generates and saves as a .SQL script. The variable $ScriptRoot is the 'root' directory that contains the file obectOrder.txt.

The file objectOrder.txt is a list of the individual scripts in the format of path\filename. Path is relative to $ScriptRoot, so if the value of $ScriptRoot is 'C:\Users\username\My Documents\SQL' and objectOrder.txt had a row that read 'tables\mytable.sql' then there should be a script named 'mytable.sql' in the directory 'C:\Users\username\My Documents\SQL\tables\'

The code below makes sure that all scripts listed in objectOrder.txt exist in their respective folders and also makes sure that all scripts in the defined folders are listed in objectOrder.txt (to make sure a developer does not add a script to the project but not to the objectOrder.txt file.

Right now, the PowerShell script executes in the directory defined by the variable $ScriptRoot, but if I move it, then it no longer will work, as it is looking for files off the execution path.

I want to revise the code below so it will still function properly (i.e. all paths/files are relative to $ScriptRoot) regardless of where the PowerShell script is located. It is probably a relatively simple change but I've played around with it quite a bit and all I've succeeded in doing is generating a lot of errors.

	$objectOrder = "$ScriptRoot\objectOrder.txt"
	$fileList = Get-Content -Path $objectOrder
	$directoryList = $fileList | %{ $_.split("\")[0]} | select -unique
	$files = $directoryList | %{ Get-ChildItem $_ } | ?{ $_.extension -eq ".sql" } | %{"$(\$_.Directory.Name)\$($_.Name)" }

	# compares files in tables directory to provided list, shows differences and offers the option of exiting the script if
	# there are. the option to continue should only be chosen if all files in the list are present in the tables folder
	$fileDiff = Compare-Object $fileList $files
	if ($fileDiff) {
		Write-Host "`n"
		Write-Host "Please Verify the following files have both a list entry and a file: `n`n"
		$fileDiff | foreach {
			if ($_.SideIndicator -eq "=>") {
				$_.InputObject + "  (file not listed in ojbectOrder.txt)"
			} 
			else {
				$_.InputObject + "  (listed file not located in indicated directory)"
			}
		}

		if (!$NoHead)
			{
			throw "Incongruity between objectOrder.txt and directory structure/files"
			}
		else
			{
			$title="objectOrder.txt Missing!"
			$message = "Continuing with missing files will likely produce errors.`nChoose 'Yes' only if all files in the list are present.`n`nNote: It is NOT recommended that you continue`nwithout resolving the missing files!"
			$continue = [system.windows.forms.messagebox]::show($message,$title, "YesNo", "Warning", "Button2", "ServiceNotification")
			switch ($continue)
				{
				"Yes" {}
				"No" {throw "Exiting due to user response! Missing table file(s) detected."}
				}
			}
		}

Open in new window

0
Comment
Question by:dbbishop
  • 2
  • 2
4 Comments
 
LVL 39

Accepted Solution

by:
footech earned 500 total points
ID: 40366504
Unless the current directory is $scriptroot, then on line 7 "Get-ChildItem $_" won't work.  Also, there is an extra backslash in there which shouldn't be (corrected below).
%{"$($_.Directory.Name)\$($_.Name)" }

Open in new window

There are two choices to correct the "Get-ChildItem $_" bit; either
- change location to $scriptroot before running that command, or
- submit the full path to Get-ChildItem, i.e.
$files = $directoryList | %{ Get-ChildItem (Join-Path $ScriptRoot $_) } | ?{ $_.extension -eq ".sql" } | %{"$($_.Directory.Name)\$($_.Name)" }

Open in new window

0
 
LVL 15

Author Comment

by:dbbishop
ID: 40366707
The extra backslash was a remnant of me trying to figure out how to get the full path and not the original code. Thanks for pointing it out.

I like the idea (why didn't I think of it) of just chaging the location. DUH!! Although asking this question exposed me to Join-Path. How in the world does one remember all this stuff. I'm doing good to remember how to load PowerShell :-)
0
 
LVL 15

Author Closing Comment

by:dbbishop
ID: 40366811
Thanks. I just used set-location after I processed the parameter file (didn't mention that part, did I). Works like a charm. I think I tried to over-complicate the task at hand :-)
0
 
LVL 39

Expert Comment

by:footech
ID: 40366819
It's about as easy to use the -join operator as it is to use Join-Path (and -split instead of Split-Path), and there's been times where I've forgotten about certain cmdlets, or nuances of different operators.  Being exposed to questions from others that I wouldn't have to deal with in my day-to-day work helps me to remember a lot of stuff that I would otherwise probably forget.  I also find that I revisit certain help topics repeatedly.  Even browsing a list of cmdlets can help.  :)
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Utilizing an array to gracefully append to a list of EmailAddresses
Set OWA language and time zone in Exchange for individuals, all users or per database.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

758 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

19 Experts available now in Live!

Get 1:1 Help Now