0

I want import powershell cmd stored in txt file var1.txt inside a scr3.ps1 script inside Powershell ISE and execute the cmds.

var1.txt file data

time=(Get-Date).AddYears(-1)
extn=@("*.mp3", "*.jpg")
path=E:\marathi\Lavani

scr3.ps1 file data

$ConfigFile = "E:\marathi\Lavani\var1.txt"
#Creating an empty hash table
$ConfigKeys = @{}


#Pulling, separating, and storing the values in $ConfigKey
Get-Content $ConfigFile | ForEach-Object {

$Keys = $_ -split "="

$ConfigKey += @{$Keys[0]=$Keys[1]}
}

$extn2 = $ConfigKey.extn
$path2 = $ConfigKey.path
$time2 = $ConfigKey.time

$time2
$extn2
$path2

Get-ChildItem -Include $extn2 -Path $path2 -Recurse | Where-Object {($_.LastWriteTime -lt $time2)}

the output of $time2, $extn2, $path2 is as follows

(Get-Date).AddYears(-1)
@("*.mp3", "*.jpg")
E:\marathi\Lavani

But the required output is

26 May 2022 11:32:46 AM
*.mp3
*.jpg
E:\marathi\Lavani

how to import PowerShell command from txt file into PowerShell .ps1 file and execute the commands as well?

Shreya Patil
  • 3
  • 1
  • 2
  • Does this answer your question? [powershell: how to evaluate a string](https://stackoverflow.com/questions/4836703/powershell-how-to-evaluate-a-string) – Luuk May 26 '23 at 06:34
  • Have a look at [`ConvertFrom-StringData`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-stringdata?view=powershell-7.3). – stackprotector May 26 '23 at 06:38

1 Answers1

1

I would recommend you to turn your txt into a ps1 file.

The content would be

$time = (Get-Date).AddYears(-1)
$extn = @("*.mp3", "*.jpg")
$path = E:\marathi\Lavani

And in the beginning of your main script, add this

$ConfigFile = "E:\marathi\Lavani\var1.ps1"
.$ConfigFile

Now the output should be as expected.

  • Thanks The script is working now but receiving error . : File E:\marathi\Lavani\src3.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 + . E:\marathi\Lavani\src3.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess – Shreya Patil May 26 '23 at 09:18
  • @ShreyaPatil, that is an unrelated problem - see https://stackoverflow.com/q/4037939/45375 – mklement0 May 26 '23 at 12:08