Reputation: 49
I have a script with an .XML file in a folder. Script can run and work its magic with an .XML file.
For now, this script is only able to run, if I place this folder on a desktop, but I would like to be able to run it from anywhere in the computer, as long as long both files are in this directory and directory´s name doesn´t change.
How can I do that?
Here is my script:
<# 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
}
Upvotes: 1
Views: 77
Reputation: 58971
We wouldn't be able to answer your question without the script. In gernal, you have to check your script for hardcoded path and replace them with a Join-Path
of your determined script directory:
<# 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")
}
Also, you can improve your script a lot. You can read the content of the file once, store it in a variable and replace / set the content for each copy you want:
$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")
}
Upvotes: 0
Reputation: 354644
You can get information about the script currently running via $PSCommandPath
:
Split-Path -Parent $PSCommandPath
You can then combine that with your XML file name via Join-Path
:
$scriptPath = Split-Path -Parent $PSCommandPath
$xmlPath = Join-Path $scriptPath foo.xml
Upvotes: 1