powershellcsvlocked-filesselect-string

Powershell move-item file in use


Trying to match a string in a bunch of CSV files and then move those with the string to another folder. The script logic seems to work but I keep getting errors that the file is use. I imagine it is powershell that has the file locked. How can I work around this?

$DestDir = "C:\temp\NEWCSV"
$SrcDir = "C:\temp\CSV"
$SearchString = "teststring"
gci $SrcDir -filter *.csv | select-string $SearchString | select path | move-item -dest $DestDir -whatif

Solution

  • I'm not sure why your script doesn't work, unless the Select-String is keeping the file open as an object being passed down the pipe. If you rephrase it like this it'll work:

    $DestDir = "C:\temp\NEWCSV"
    $SrcDir = "C:\temp\CSV"
    $SearchString = "TITLE"
    gci $SrcDir -filter *.csv | ?{select-string $SearchString $_ -quiet}|move-item -Destination $DestDir