stef
stef

Reputation: 99

Executing a command with string doesn't work in powershell

This is my code and it doesn't work:

$brisanje=dat.txt, dat2.txt
Remove-Item $brisanje

The error that I get here is

Remove-Item : Cannot find path 'C:\Users\stefan\Desktop\brisanjedat\dat.txt, dat2.txt' because it does not exist.

But when I write it like this it works like a charm:

Remove-Item dat.txt, dat2.txt

I've been stuck with this problem for hours, any solutions?

Upvotes: 3

Views: 806

Answers (2)

Bill Kindle
Bill Kindle

Reputation: 169

It's also a good idea to use dot (.) sourcing in your code too. Shells and Scripts have different scopes, and when you dot source variables you combine the two. I dot source everything, especially if I'm using it over and over again or in different environments.

cd C:\Users\stefan\Desktop\brisanjedat\ $brisanje= ".\dat.txt",".\dat2.txt" Remove-Item $brisanje

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

The PowerShell parser has two modes, depending on context.

When in an argument mode context (like in the case of Remove-Item dat.txt,dat2.txt), it treats the bare words as a list of expandable strings.

In expression mode (the default), a bare word at the start of an expression is treated like a command and powershell will attempt to resolve it, which is why you see the error.

Use quotes to make sure the parser knows you mean dat1.txt,dat2.txt to be a string array:

$brisanje="dat.txt","dat2.txt"

See the output from Get-Help about_Parsing for more information

Upvotes: 5

Related Questions