Solved

PowerShell Query Help

Posted on 2014-10-07
4
155 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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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 …
How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

867 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

26 Experts available now in Live!

Get 1:1 Help Now