PowerShell Query Help

Posted on 2014-10-07
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"
			$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 = []::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

Question by:dbbishop
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
LVL 40

Accepted Solution

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

LVL 15

Author Comment

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 :-)
LVL 15

Author Closing Comment

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 :-)
LVL 40

Expert Comment

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.  :)

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Create and license users in Office 365 in bulk based on a CSV file. A step-by-step guide with PowerShell script examples.
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

740 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