Syntax error using [void]
Trying to use [void] to supress output of Move-Item cmdlet:
foreach ( $f in $Files ) {
[void] Move-Item $f.fullname $TargetPath
}
Error:
At C:\!\!PS\x.ps1:2 char:10
+ [void] Move-Item $f.fullname $TargetPath
+ ~~~~~~~~~
Unexpected token 'Move-Item' in expression or statement.
What's going on here? Thanks.
[edit] I just realized that move-item doesn't produce output if everything works - this snippet was part of a bigger block of code that produced chatter that I needed to void. So I can remove the void, but I'm still interested to know what's going on.
25 comments · 63% upvoted · other discussions
In powershell, just use the
$nullvariable in these contexts:time_keeper_1 2 points · Nov 2022
I don’t understand this. Why do we assign that action to $null.
SMFX 8 points · Nov 2022
The
$nullis a special variable that must always equal nothing. Functionality wise, it's essentially the same as piping to| Out-Null, but has been proven to be exceptionally faster in repetitive loops.lolinux 3 points · Nov 2022
When assigning the output stream to a variable, it will no longer be sent to the standard output, but will be saved in the variable.
However be aware that it's just the standard output stream. If there are errors, the error stream will stil be sent to the screen.
In order to make it silent you could
Move-Item $file $newname -ErrorAction SilentlyContinue, or capture the error stream into a variableMove-Item $file $newname -ErrorVariable errvar.Edit: formatting
time_keeper_1 2 points · Nov 2022
Thank you. This community is great. I’m on my first week of posh from C# and I’m learning a lot.
SMFX 2 points · Dec 2022
Or, if you are going to do error handling, incorporate
try { } catch { }and use-ErrorAction Stop:lolinux 1 points · Dec 2022
Yeah, that too is a good idea, since OP knows C#, I imagine error handling should be familiar
[deleted] 0 points · Dec 2022
Or simply
Which is more elegant
SMFX 1 points · Dec 2022
See below: https://www.reddit.com/r/PowerShell/comments/z8banm/syntax_error_using_void/iybejrz?utm_medium=android_app&utm_source=share&context=3
jimb2 [OP] 1 points · Nov 2022
Will do this. I like the look of [void] but not if I have to bracket the cmdlet. My full code was moving huge directories - like 300k files - in to a subfolder structure and needed to create the subfolders like
The void worked with the dotnet function but not with the cmdlet.