Powershell 脚本可以从任何文件夹运行

Powershell 脚本可以从任何文件夹运行,powershell,Powershell,我在文件夹中有一个带有.XML文件的脚本。脚本可以运行并使用.XML文件发挥其魔力 现在,这个脚本只能运行,如果我把这个文件夹放在桌面上,但我希望能够从计算机中的任何地方运行它,只要两个文件都在这个目录中并且目录的名称不变 我该怎么做 这是我的剧本: <# Makes a copy of a former file and replaces content of a <serviceNumber> tag with a name of the copied file #>

我在文件夹中有一个带有.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
}

$SetCount=读取主机-提示“您需要多少副本”
$name=420566666000
对于($i=1;$i-le$SetCount;$i++)
{ 
$name++
复制项目$env:USERPROFILE\Desktop\numbers\420566666000.xml$env:USERPROFILE\Desktop\numbers\$name.xml
(获取内容$env:USERPROFILE\Desktop\numbers\$name.xml)。替换('420566666000',$name)|设置内容$env:USERPROFILE\Desktop\numbers\$name.xml
}

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

<# 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")
}

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

Split-Path -Parent $PSCommandPath
然后,您可以通过
连接路径将其与XML文件名组合:

$scriptPath = Split-Path -Parent $PSCommandPath
$xmlPath = Join-Path $scriptPath foo.xml

与我们分享您的脚本,我们可以帮助您。我已将脚本添加到问题本身。Hover,我想知道如何解决这个问题,不仅仅是针对这个特定的脚本,尽管这也会很有帮助:)谢谢你们两位的建议,以及对我的脚本的改进。您是对的,一次读取文件的内容更有意义。我还将阅读一些关于
Split Path
/
Join Path
的内容,我还不知道如何正确使用它们。请注意,使用
$MyInvocation
只能在脚本的顶层工作。您不能以相同的方式从函数中使用它(因为此时的调用是函数调用,而不再是脚本调用)。因此,在本例中它是有效的,但一旦他们试图通过创建一个
Get ScriptPath
函数来抽象出一些东西来使用,它就会停止工作。
$scriptPath = Split-Path -Parent $PSCommandPath
$xmlPath = Join-Path $scriptPath foo.xml