Brian Rowland
Brian Rowland

Reputation: 41

How do I use PowerShell within a batch file FOR command?

I'm trying to generate a date string for an LDAP query compatible with the Active Directory whenChanged field. I'm pulling AD data into CSV using CSVDE and need an LDAP query that will filter the results to those items changed within the last 2 days. I pieced together the following FOR command to generate the first part of the comparison string based on a few examples found here on Stack Overflow:

FOR /F "usebackq" %i in (`PowerShell $date^= [DateTime]::Today.AddDays^(-2^)^; $date.ToString^('yyyyMMdd'^)`) DO SET daysAgo = %i

This FOR command works fine from the command prompt, but bombs inside a batch script, w/ the following output:

:Today.AddDays(-2); was unexpected at this time.

What's causing the command to bomb? Thanks.

Upvotes: 4

Views: 660

Answers (1)

Anthony Mastrean
Anthony Mastrean

Reputation: 22404

I'm stealing his juice... FOR iterator variables in a batch file need to have a double percent sign, %%. So, your line would look like this

FOR /F "usebackq" %%i in (<snipped-powershell-command>) DO SET daysAgo=%%i

Upvotes: 2

Related Questions