Powershell: Specify file path as variable

旧巷老猫 提交于 2019-12-13 18:27:03

问题


I am running the following SQL query through a powershell script and need to run the script multiple times against different files. So what I am trying to figure out is how to specify a file path as a variable when I run the script?

update [$Db_name].[dbo].[$BatchTable]
set [$Db_name].[dbo].[$BatchTable].Wave = 'Wave1.1'
from [$Db_name].[dbo].[$BatchTable]
inner join OPENROWSET(BULK 'FilePath\file.csv',    
FORMATFILE= 'E:\import.xml') AS a
on ([$Db_name].[dbo].[$BatchTable].Name= a.Name) and  
([$Db_name].[dbo].[$BatchTable].Domain = a.Domain)

The 'FilePath\file.csv' is the file path I need to define as a variable so that my code would instead look like this:

inner join OPENROWSET(BULK '$INPUTFILEPATH',    
FORMATFILE= 'E:\import.xml') AS a

Any help or potentially better methods to accomplish this would help very much.

From the command like I want to be able to run the script like this:

CMD: updatescript.ps1 $INPUTFILEPATH = C:\Documents\myfile.csv

Again, I'm not sure this is the best way to go about this?


回答1:


You're nearly there. You will need to add a parameter block at the very start of your script e.g.

Param( 
[Parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_ -PathType 'leaf'})]  
[string] $InputFilePath  
)

This creates a mandatory (not optional) string parameter, called InputFilePath, and the ValidateScript is code used to validate the parameter, in this case checking the file exists using the Test-Path cmdlet and pathtype of leaf (if checking existence of a directory use 'container').

When running your script use the syntax below:

updatescript.ps1 -INPUTFILEPATH "C:\Documents\myfile.csv"

and in the script use the variable as the path exactly as in your question:

inner join OPENROWSET(BULK '$INPUTFILEPATH',    
FORMATFILE= 'E:\import.xml') AS a

NOTE: in powershell when using parameters when running a script you only need to use the least amount of characters that uniquely identify that parameter from all the others in your param block - in this case -I works just as well as -InputFilePath.




回答2:


You can pass command line parameters to the powershell script using param.

Example:

param(
   [string]$INPUTFILEPATH
)

And then call the script as follows:

updatescript.ps1 -INPUTFILEPATH C:\Documents\myfile.csv

More details about cmd line parameters can be found here



来源:https://stackoverflow.com/questions/29955774/powershell-specify-file-path-as-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!