简体   繁体   中英

How can I pass negative numbers to a net files call in PowerShell

I have a script which closes files on a network share.

now, whenever a negative file ID like this -335362046 gets returned, my command doesn't work anymore.

I guess PowerShell thinks that the number is a parameter because of the - at the beginning. How do I properly escape this out to make my call work for both positive and negative numbers??

net files $_.ID /close > $null

File IDs can't be negative. The software that lists the file IDs is showing you an int32 (signed integer) when it should have used uint32, so the bit to the left (32th bit)'s value of 1 makes the number negative instead of adding 2147483648 .

You need to convert it, ex:

function closefilehandle ($id) {
    Write-Host "ID = $id"

    #If negative id, convert to uint32
    if($id -lt 0) { $id = [uint32]("0x{0:x}" -f $id) }

    Write-Host "Closing handle $id"
    net files $id /close

}

closefilehandle -id (-335362046)

Output:

ID = -335362046
Closing handle 3959605250
There is not an open file with that identification number.

More help is available by typing NET HELPMSG 2314.

The output is an error, but it's the right kind of error, as a negative id would give you syntax error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM