Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Command works in interface but not within a script

Tags:

powershell

Fairly new to scripting. I have a very basic script which works fine within the ISE but when I run it within a file it doesn't. Script:

#
# WPM Convert to Ascii.ps1
# Process to remove accented characters from a text file as they cause issues when importing to U4BW via GL07
# SP Jan 2019
#
# Parameters
#
$usefile    =$dir+"\"+'SPTEMP.txt'
$outfile    =$dir+"\"+'SPOUT.txt'

#
# Convert characters
#
Get-Content $usefile -replace 'a', 'A' |Set-Content $outfile 

Simply converting characters in 1 file outputting to another. Called from U4BW(Agresso) command being:-

powershell.exe -ExecutionPolicy Unrestricted -File "c:\scripts\WPM Convert to Ascii.ps1" -infile "[File name]" -dir "[Directory]"

I have debugged all the parameters sent (infile and dir) and they are fine. Tried closing the file (outfile) beforehand.

I know this is probably a basic issue but I just can't see it. Any help gratefully received! Steve

like image 306
MrPop Avatar asked Sep 13 '26 03:09

MrPop


1 Answers

You need to make the following changes to your script.

Declare this at the top of your script so the -dir parameter in your call is actually recognized in the script:

param($dir)

Also, your replace command looks wrong, -Replace is not a valid parameter of Get-Content. You probably meant this?

(Get-Content $usefile) -replace 'a', 'A' | Set-Content $outfile

Final script (with some other minor improvements):

# WPM Convert to Ascii.ps1
# Process to remove accented characters from a text file as they cause issues when importing to U4BW via GL07
# SP Jan 2019

# Passed parameters
param (
    # The base directory path
    $dir
)

# Derived parameters
$usefile = Join-Path $dir "SPTEMP.txt"
$outfile = Join-Path $dir "SPOUT.txt"

# Replace characters
(Get-Content $usefile) -replace 'a', 'A' | Set-Content $outfile 

Then call it like this:

powershell.exe -ExecutionPolicy Unrestricted -File "c:\scripts\WPM Convert to Ascii.ps1" -dir "[Directory]"
like image 63
marsze Avatar answered Sep 16 '26 07:09

marsze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!