脚本能够从任何文件夹运行

时间:2016-11-23 08:13:06

标签: powershell

我在一个文件夹中有一个带有.XML文件的脚本。脚本可以运行并使用.XML文件运行它的魔力。

目前,如果我将此文件夹放在桌面上,此脚本只能运行,但我希望能够从计算机的任何位置运行它,只要两个文件都在此目录中并且目录的名称没有改变。

我该怎么做?

这是我的剧本:

<# Makes a copy of a former file and replaces content of a <serviceNumber> tag with a name of the copied file #>
$SetCount = Read-Host -Prompt "How many copies do you need"
$name = 420566666000
for ($i=1; $i -le $SetCount; $i++)
{ 
$name++    
Copy-Item $env:USERPROFILE\Desktop\numbers\420566666000.xml $env:USERPROFILE\Desktop\numbers\$name.xml
(Get-Content $env:USERPROFILE\Desktop\numbers\$name.xml).replace('420566666000', $name) | Set-Content $env:USERPROFILE\Desktop\numbers\$name.xml
}

2 个答案:

答案 0 :(得分:1)

您可以通过$PSCommandPath获取有关当前正在运行的脚本的信息:

Split-Path -Parent $PSCommandPath

然后,您可以通过Join-Path

将其与您的XML文件名相结合
$scriptPath = Split-Path -Parent $PSCommandPath
$xmlPath = Join-Path $scriptPath foo.xml

答案 1 :(得分:0)

如果没有脚本,我们将无法回答您的问题。在gernal中,您必须检查脚本中的硬编码路径,并将其替换为您确定的脚本目录的Join-Path

<# Makes a copy of a former file and replaces content of a <serviceNumber> tag with a name of the copied file #>
$SetCount = Read-Host -Prompt "How many copies do you need"

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

$name = 420566666000
for ($i=1; $i -le $SetCount; $i++)
{ 
$name++    
Copy-Item (Join-Path $scriptPath '420566666000.xml') (Join-Path $scriptPath "$name.xml")
(Get-Content (Join-Path $scriptPath "$name.xml")).replace('420566666000', $name) | Set-Content (Join-Path $scriptPath "$name.xml")
}

此外,您可以改进您的脚本。您可以读取文件的内容一次,将其存储在变量中并替换/设置所需的每个副本的内容:

$SetCount = Read-Host -Prompt "How many copies do you need"
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

$name = 420566666000
$fileContent = Get-Content (Join-Path $scriptPath '420566666000.xml') -Raw

for ($i=1; $i -le $SetCount; $i++)
{   
    $name++;
    $fileContent -replace '420566666000', $name | Set-Content (Join-Path $scriptPath "$name.xml")
}