VMware Cloud Community
SaqiChangx
Enthusiast
Enthusiast
Jump to solution

Setting File for Powershell.

Hi everyone.

I like to make my script more flexible and easier to manage or edit. For this reason I try to create an external ConfigFile or Setting file (XML or other options). This config file contains variables like path variables or some others, and the values of the variables are called in the main script.

I would appreciate any kind of suggestions or help.

like:

XML-File

path = 😧 \users\folder\....

2path = D:\..\..\

3path=D:\..\..

and sample ps1 script:

import = XML-File

Get-ItemChild -Path $path

Get-ItemChild -path $2path

Report = $3path

I hope, it's not much confusing. :smileylaugh: Otherwise, i can explain it again.

1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Personally I prefer JSON for such files.
They are easier to read and edit with an editor, imho.

To create such a file

$data = @{

  Path1 = 'C:\Folder1'

  Path2 = 'C:\Folder2'

  Path3 = 'C:\Folder3'

}

$data | ConvertTo-Json | Out-File -FilePath .\config.json

To use such a file

$config = Get-Content -Path .\config.json | ConvertFrom-Json

Get-ChildItem -Path $config.Path1

And the file itself is very simple to read and edit

json.jpg


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

4 Replies
LucD
Leadership
Leadership
Jump to solution

Do you intend to create/update that XML file with a PowerShell script?

But first, why XML?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
SaqiChangx
Enthusiast
Enthusiast
Jump to solution

no, in the XML file I store my data, such as the location of files, and from this file(xml) I fetch the value of a variable

it must not be an XML file. I just found out that XML can be imported into PowerShell script, so I mention it.

It sounds like object-orientation

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Personally I prefer JSON for such files.
They are easier to read and edit with an editor, imho.

To create such a file

$data = @{

  Path1 = 'C:\Folder1'

  Path2 = 'C:\Folder2'

  Path3 = 'C:\Folder3'

}

$data | ConvertTo-Json | Out-File -FilePath .\config.json

To use such a file

$config = Get-Content -Path .\config.json | ConvertFrom-Json

Get-ChildItem -Path $config.Path1

And the file itself is very simple to read and edit

json.jpg


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

SaqiChangx
Enthusiast
Enthusiast
Jump to solution

Thank you Sir,

0 Kudos