I can’t seem to get this correct. Maybe fresh eyes?
This command works in a non-elevated Powershell window to change the last modified date of a file:
(get-item "C:\users\ron\nwfundpositions.csv").lastwritetime=("16 Jun 2023 18:00:00")
I am trying to run the same command from VBA:
strCommand = "powershell " & PSline
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(strCommand)
In the code above, I have constructed strCommand to produce either:
powershell `"(get-item C:\Users\ron\NWFundPositions.csv.lastwritetime=(`"16 Jun 2023 18:00`")
or
powershell `"(get-item C:\Users\ron\NWFundPositions.csv.lastwritetime=(`"16 Jun 2023 18:00`")`"
In both cases, StdErr returns a message that there is a Missing closing parenthesis ')' in expression
What am I missing?
Thanks
>Solution :
The verbatim command line you pass to WshShell.Exec() must look like this:
powershell (Get-Item \"C:\users\ron\nwfundpositions.csv\").LastWriteTime=\"16 Jun 2023 18:00:00\"
-
On its command line,
powershell.exe, the Windows PowerShell CLI, requires"characters that are to be be preserved as part of a PowerShell command to execute to be escaped as\"; unescaped"chars. are removed during the initial command-line parsing.`"only works in PowerShell code; if you need specify such an escaped"on the command line (not necessary here), you need to use`\"(sic).
-
Everything after
powershellis considered the value for the (implied)-Commandparameter. Since no shell is involved when calling viaWshShell.Exec(), enclosing the command in"..."overall isn’t strictly necessary in this case, though such enclosure is required if whitespace normalization must be prevented (multiple spaces turning into one).
Alternatively, you can use '...' quoting, given that your string values do not require expansion (interpolation), and omit the optional quoting around the file path:
powershell (Get-Item C:\users\ron\nwfundpositions.csv).LastWriteTime='16 Jun 2023 18:00:00'
If the string is constructed programmatically and there’s a chance that the path contains spaces (or other PowerShell metacharacters), you do need to quote it; however, if you use '...' quoting, you must ensure that the file path doesn’t itself contain ' or, if it does, double the embedded '; Using \"...\" quoting is then the simpler alternative, given that file paths cannot contain " themselves.

