PowerShell Caratteri Speciali – Special Characters And Tokens

Site
 

$ (dollar sign)

Declare/use a variable
Example.
$abc = "123"
 

$_ (dollar underscore)

‘THIS’ token. Typically refers to the item inside a foreach loop.
Task: Print all items in a collection.
Solution.
... | foreach { Write-Host $_ }
 

$$ (double dollar, two dollars)

Last token of last command. Does NOT refer to the whole command.
Example.
Write-Host "Hello, world!"
$$

Output.
Hello, world!
Hello, world!
 

$^ (dollar sign + caret)

Thanks to Richard for accidentally finding this one.
First token of last command. Does NOT refer to the whole command.
Example.
Write-Host "Hello, world!"
$^

Output.
Hello, world!
Write-Host
 

$? (dollar sign + question mark)

Many google searches were looking for this information, so I experimentally found what it does.
Returns True or False value indicating whether previous command ended with an error. For some reason it does not catch all errors, but most of the time it works.
Task 1: See if a powershell cmdlet exists in the system.
Code.
SomeCmdLet #does not exists
$?
$?

Output.
The term ‘SomeCmdLet’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:15
+ SomeCmdLet <<<< #does not exists
+ CategoryInfo : ObjectNotFound: (SomeCmdLet:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
False #error occured – previous cmdlet (SomeCmdLet) was not found
True #no errors returned by the previous command ($?)

Task 2: See if a WMI class exists in the system
Code.
gwmi win32_processo -ErrorAction SilentlyContinue #intentional error, win32_processor is the right one
$?
$?

Output.
False
True
 

$() (dollar sign + round brackets)

Thanks to Kevin for a suggestion to add this one.
Sub-expression operator for double-quoted strings. Whatever is in the brackets should be evaluated first.
Example.
$name = "Kevin";
"Hello, $name, there are $($name.length) characters in your name"

Output.
Hello, Kevin, there are 5 characters in your name

It can be used with any expression, so this will also work:
“There are $(2+3) characters in your name”
 

${} (dollar sign + curly brackets)

Thanks to Remco for a hint about it.
Declare or use a variable with non-standard characters in it, a more generalized syntax to $variableName. It adds support for punctuation or non-English characters.
References: StackOverflow, Technet, ss64.com.
Example.
${,,,} = 5
${,,,}

Output.
5
 

| (pipeline)

Catch output of the command and pass it to another command.
Task: Get list of processes and select top 3 items.
Solution.
Get-Process | Select-Object -first 3
 

% (percentage)

1. Shortcut to foreach.
Task: Print all items in a collection.
Solution.
... | % { Write-Host $_ }

2. Same as Mod in VB.
Example:
5 % 2
 

.. (double dot)

Specify a range.
Task: Print numbers 1 through 5 without a foreach loop.
Code.
1..5
Output.
1
2
3
4
5
 

:: (double-colon)

Thanks to Darrell for asking about this one.
Reference static member of a class. The class name must be enclosed in square brackets.
Task: Compare two strings.
Code.
[string]::Equals("a", "b")
Output.
False
 

+ (plus sign)

Thanks to Cody for pointing at this feature of Powershell.
Aside from its natural use, i.e. addition of two arguments, you can also use a plus sign to reference a public nested class.
For official reference, see here. Thanks to David Brabant for help in figuring this out.
Code.
[System.Net.WebRequestMethods+Ftp]::UploadFile
Output.
STOR
 

+= (plus equals)

Thanks to Brian G.
Increments value on the left by the amount on the right (and stores result). For strings it means concatenation.
Very well known to C# developers, so not strictly a Powershell feature.
In Powershell, however, this operator has a special use – you can add elements to arrays.
Mostly syntactic sugar, the array is still recreated behind the scenes, so just to save a few characters.
Code.
$b = 1 #initialize a variable
$b += 2 #add 2
$b #output 3 (1 + 2)

$a = @(1,2,3) #initialize array with 3 elements
$a += 4 #add element number 4
$a #output 4 elements
Output.
3

1
2
3
4
 

! (exclamation mark)

Thanks to Leo for asking about this one.
Shortcut to -not.
Code.
$a = $null;
if(!$a) { Write-Host '$a is null' }

Output.
$a is null
 

? (question mark)

Output all items that conform with condition (shortcut to where). Shortcut to the following:
foreach { if (…) {return … } }
Task: Print all odd numbers between 1 and 5 (inclusive):
Code.
1..5 | ? { $_ % 2 }
Output.
1
3
5
 

` (backtick)

1. Continue command on the next line.
Code.
Write-Host `
"Hello, world!"

Output.
Hello, world!

2. Include a special symbol into a string. Available options:
`$ – include a dollar symbol in your string. If you don’t escape it, Powershell will assume you are trying to embed a variable.
`0 – Null. My preference is using $null instead.
`a – Alert. Yes, it does make sound, and you can use multiple for multiple beeps.
`b – Backspace
`f – form feed – only affects printed documents.
`n – New line
`r – Carriage return
`t – Horizontal tab
`v – Vertical tab – only affects printed documents.
`’ – Single quote – I prefer using double quotes when I need to escape a single one, since I don’t need any escaping in this case.
`” – Double quote – you can use single quotes, and you don’t need this symbol. My preference is use standard escaping instead, so 4 double quotes (“”””) means a double quote.
Official article by Microsoft with full description on every token: http://technet.microsoft.com/en-us/library/hh847835.aspx
 

# (hash sign)

Single line comment.
Example.
#This is a commented line
#This is a second one

 

<# … #> (left angle bracket / &lt + pound … pound + right angle bracket / &gt)

Block/Multi-line comment.
Example.
<#This is a commented block#>
 

& (ampersand)

Execute string as command.
Example.
& "Get-Process"
 

@( ) (email-at + round brackets)

Declare arrays.
Note: comma is used as a separator, in contrast to hash table declaration.
Example.
$a = @("One", "Two", "Three")
 

@{ } (email-at + curly brackets/braces)

Declare hash tables.
Note: semicolon is used as a separator, in contrast to array declaration.
Example.
$a = @{"1" = "one"; "2" = "two"; "3" = "three"}
 

@’ … ‘@ (email-at + single quote … single quote + email-at)

Here-string without embedded variables.
Code.
@'
$(1+2)
$(3+4)
$(5+6)
'@

Output.
$(1+2)
$(3+4)
$(5+6)
 

@” … “@ (email-at + double quote … double quote + email-at)

Here-string with embedded variables or other code bloc from other language like C# C++.
Code.
@"
$(1+2)
$(3+4)
$(5+6)
"@

Output.
3
7
11

Annunci

SID Microsoft Predefiniti

SID Values For Default Windows NT Installations

SUMMARY
Many User Accounts, Local Groups, and Global Groups have a default Security Identifier (SID) or Relative Identifier (RID) value across all installations of Windows NT. These values can be displayed by using the utility Getsid.exe from the Windows NT Resource Kit.

MORE INFORMATION
The following information was taken from a Domain Controller named DomainName. The default groups differ on a Windows NT Workstation or Server installation, and if they are not a member of a domain, then the computer name would be considered the authority.

The values below that have a full SID value will differ on all installations, but the RID value at the end of the SID is the same across all installations.

NOTE: The values in parentheses is the hexadecimal values of the RID.
Built-In Users

DOMAINNAME\ADMINISTRATOR
S-1-5-21-917267712-1342860078-1792151419-500 (=0x1F4)

DOMAINNAME\GUEST
S-1-5-21-917267712-1342860078-1792151419-501 (=0x1F5)

Built-In Global Groups

DOMAINNAME\DOMAIN ADMINS
S-1-5-21-917267712-1342860078-1792151419-512 (=0x200)

DOMAINNAME\DOMAIN USERS
S-1-5-21-917267712-1342860078-1792151419-513 (=0x201)

DOMAINNAME\DOMAIN GUESTS
S-1-5-21-917267712-1342860078-1792151419-514 (=0x202)

Built-In Local Groups

BUILTIN\ADMINISTRATORS S-1-5-32-544 (=0x220)
BUILTIN\USERS S-1-5-32-545 (=0x221)
BUILTIN\GUESTS S-1-5-32-546 (=0x222)
BUILTIN\ACCOUNT OPERATORS S-1-5-32-548 (=0x224)
BUILTIN\SERVER OPERATORS S-1-5-32-549 (=0x225)
BUILTIN\PRINT OPERATORS S-1-5-32-550 (=0x226)
BUILTIN\BACKUP OPERATORS S-1-5-32-551 (=0x227)
BUILTIN\REPLICATOR S-1-5-32-552 (=0x228)

Special Groups

\CREATOR OWNER S-1-3-0
\EVERYONE S-1-1-0
NT AUTHORITY\NETWORK S-1-5-2
NT AUTHORITY\INTERACTIVE S-1-5-4
NT AUTHORITY\SYSTEM S-1-5-18
NT AUTHORITY\authenticated users S-1-5-11 *
NT AUTHORITY\LOCAL SERVICE S-1-5-19
NT AUTHORITY\NETWORK SERVICE S-1-5-20

* For Windows NT 4.0 Service Pack 3 and later only
Back to the topBack to the top | Give Feedback

Properties
Article ID: 163846 – Last Review: November 1, 2006 – Revision: 2.1
APPLIES TO

Microsoft Windows NT Workstation 3.5
Microsoft Windows NT Workstation 3.51
Microsoft Windows NT Workstation 4.0 Developer Edition
Microsoft Windows NT Server 3.5
Microsoft Windows NT Server 3.51
Microsoft Windows NT Server 4.0 Standard Edition

Keywords:
kbinfo kbnetwork KB163846

VLC Lavagna Luminosa

Come Utilizzare VLC Media Player e una WebCam installata su un minicavalletto come Lavagna Luminosa.

WebCam Utilizzata

Device name: Logitech HD Pro Webcam C920
USB Vendor ID (VID): 0x046D
USB Product ID (PID): 0x082D
USB Revision (BCD): 0x0011
Firmware Version: 7.5.1023
Firmware CRC: 0xFFFF
EEPROM Version: 0.0
Sensor Type: 4.38
Driver Version: 13.80.853.0

Aprire VLC Media Player, scegliere “Media->Apri Periferica di Acquisizione”

01

Modalità Acquisizione: “DirectShow” dshow://
Nome del Dispositivo Video: “La web cam che si intende utilizzare come Lavagna Luminosa”
Periferica Audio: “None”
Mettere la spunta “Mostra altre opzioni”

02

Creare un link per attivare direttamente la lavagna luminosa, questo modo automatico per avviare vlc come lavagna luminosa è utile per avere un output a video immediato del foglio che si vuole proiettare.
copiare il link dal menu “tutti i programmi” di vlc media player sul desktop e rinominiamolo come “lavagna”, accedere alle proprietà del link (dx mouse->proprietà) alla voce “Destinazione:” aggiungere il testo visualizzato in altre opzioni: “MRL” “Modifica opzioni”, ma mettere le virgolette per racchiudere le stringhe che identificano i dispositivi audio e video nella voce “Modifica opzioni” della scheda di “Apri Media” di VLC.

Esempio:

Destinazione: "C:\Program Files\VideoLAN\VLC\vlc.exe" dshow:// :dshow-vdev="Logitech HD Pro Webcam C920" :dshow-adev="none" :live-caching=300

04

Poi Accedere alle “Opzioni Avanzate” e mettere la spunta “Proprietà del dispositivo”, all’avvio della riproduzione permette di configurare il driver della webcam per impostare il fuoco fisso, la messa a fuoco e lo zoom.

03

Prima di premere riproduci copiare in un file di testo la riga “Modifica opzioni” del pannello “Apri media”, ora premere riproduci e automaticamente si apriranno le impostazioni del driver e le proprietà di acquisizione.

05

Impostare le “Proprietà” come da immagine e fare ok, quando si avvia la riproduzione aggiustare messa a fuoco e zoom e salvare le impostazioni del driver, per automatizzare la possibilità di configurare il driver si può fare un file .cmd con la riga di codice seguente aggiungiendo le opzioni copiate precedentemente sul file di testo, ma con attenzione alle virgolette per i parametri tipo stringa come indicato dal command-line help di VLC e alle proprietà che non hanno lo stesso valore di quelle impostate dalla scheda “Proprietà”, ad esempio :dshow-fps=0 differente dai 30 “FPS” scelti prima.

start /B "VLC Lavagna" /D "C:\Program Files\VideoLAN\VLC" /I vlc.exe dshow:// :dshow-vdev="Logitech HD Pro Webcam C920" :dshow-adev="none"  :dshow-aspect-ratio="16\:9" :dshow-chroma= :dshow-fps=30 :dshow-config :no-dshow-tuner :dshow-tuner-channel=0 :dshow-tuner-frequency=0 :dshow-tuner-country=0 :dshow-tuner-standard=0 :dshow-tuner-input=0 :dshow-video-input=-1 :dshow-video-output=-1 :dshow-audio-input=-1 :dshow-audio-output=-1 :dshow-amtuner-mode=1 :dshow-audio-channels=0 :dshow-audio-samplerate=0 :dshow-audio-bitspersample=0 :live-caching=300

Al link “lavagna” creato precedentemente aggiungere un paio di opzioni per avere una riproduzione ottimale.

Destinazione: "C:\Program Files\VideoLAN\VLC\vlc.exe" dshow:// :dshow-vdev="Logitech HD Pro Webcam C920" :dshow-adev="none" :dshow-aspect-ratio=16:9 :dshow-fps=30 :live-caching=300

Pesto Erbe Aromatiche

Per una persona

1 stelo di erba cipollina
la punta di 4 rametti di maggiorana
la punta di 2 rametti di timo
La punta di un rametto di rosmarino
2 foglie di salvia
2 cucchiai d’olio extravergine d’oliva
4 cucchiai d’acqua bollente
mezzo cucchiaino di sale
150g di spaghettone quadrato cotto in abbondante acqua salata bollente
Abbondante Parmigiano Reggiano

Powershell Disabilitare i Tasti della Tastiera

Facendo riferimento a questi due link: HowToGeek e Microsoft e con l’ausilio di questo software per individuare i codici esadecimali dei tasti ho prodotto il seguente codice in powershell

 

Disablekeys.ps1

Param(
		[ValidateSet("enable","disable")]
		[String] 
		$Parametro
	) 

if($Parametro = "enable")
{
	if(gp -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Keyboard Layout" | Select-Object -ExpandProperty "Scancode Map")
	{
		$percs = @("HKLM:\SYSTEM\CurrentControlSet\Control\Keyboard Layout") | % { if($KeyName = gi -Path $_  | Select-Object -ExpandProperty Property | Where-Object {$_ -match "Scancode Map"}) {Set-ItemProperty -Path $_ -Name $KeyName -Value ([byte[]] (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF6,0x00,0x00,0x00,0x00,0x00,0x5B,0xE0,0x00,0x00,0x5C,0xE0,0x00,0x00,0x1D,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x47,0xE0,0x00,0x00,0x1D,0xE0,0x00,0x00,0x38,0xE0,0x00,0x00,0x3B,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x3D,0x00,0x00,0x00,0x3E,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x41,0x00,0x00,0x00,0x42,0x00,0x00,0x00,0x43,0x00,0x00,0x00,0x43,0x00,0x00,0x00,0x44,0x00,0x00,0x00,0x57,0x00,0x00,0x00,0x58,0x00,0x00,0x00,0x00,0x00)) -Type Binary}}
	}
	else
	{
	Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Keyboard Layout" -Name "Scancode Map" -Value ([byte[]] (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF6,0x00,0x00,0x00,0x00,0x00,0x5B,0xE0,0x00,0x00,0x5C,0xE0,0x00,0x00,0x1D,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x47,0xE0,0x00,0x00,0x1D,0xE0,0x00,0x00,0x38,0xE0,0x00,0x00,0x3B,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x3D,0x00,0x00,0x00,0x3E,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x41,0x00,0x00,0x00,0x42,0x00,0x00,0x00,0x43,0x00,0x00,0x00,0x43,0x00,0x00,0x00,0x44,0x00,0x00,0x00,0x57,0x00,0x00,0x00,0x58,0x00,0x00,0x00,0x00,0x00)) -Type Binary
	}
	Restart-Computer -Force
}
else if($Parametro = "disable")
{
	Remove-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Keyboard Layout" -Name "Scancode Map"
	Restart-Computer -Force
}

Stringa utilizzata e adattata per powershell

00000000 00000000 F600 0000 0000 5BE0 0000 5CE0 0000 1D00 0000 3800 0000 47E0 0000 1DE0 0000 38E0 0000 3B00 0000 3C00 0000 3D00 0000 3E00 0000 3F00 0000 4000 0000 4100 0000 4200 0000 4300 0000 4300 0000 4400 0000 5700 0000 5800 0000 00000000

Dal Sito Microsoft:

Scan code mapper for keyboards

In Microsoft Windows operating systems, PS/2-compatible scan codes provided by an input device are converted into virtual keys, which are propagated through the system in the form of Windows messages. If a device produces an incorrect scan code for a certain key, the wrong virtual key message will be sent. This can be fixed by writing a filter driver that analyzes the scan codes generated by firmware and modifies the incorrect scan code to one understood by the system. However, this is a tedious process and can sometimes lead to severe problems, if errors exist in the kernel-level filter driver.

Windows 2000 and Windows XP include a new Scan Code Mapper, which provides a method that allows for mapping of scan codes. The scan code mappings for Windows are stored in the following registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout

Note There is also a Keyboard Layouts key (notice the plural form) under the Control key, but that key should not be modified.

In the Keyboard Layout key, the Scancode Map value must be added. This value is of type REG_BINARY (little Endian format) and has the data format specified in the following table.
Start offset (in bytes) Size (in bytes) Data
0 4 Header: Version Information
4 4 Header: Flags
8 4 Header: Number of Mappings
12 4 Individual Mapping
… … …
Last 4 bytes 4 Null Terminator (0x00000000)

The first and second DWORDS store header information and should be set to all zeroes for the current version of the Scan Code Mapper. The third DWORD entry holds a count of the total number of mappings that follow, including the null terminating mapping. The minimum count would therefore be 1 (no mappings specified). The individual mappings follow the header. Each mapping is one DWORD in length and is divided into two WORD length fields. Each WORD field stores the scan code for a key to be mapped.

Once the map is stored in the registry, the system must be rebooted for the mappings to take effect. Note that if the mapping of a scan code is necessary on a keypress, the step is performed in user mode just before the scan code is converted to a virtual key. Doing this conversion in user mode can present certain limitations, such as mapping not working correctly when running under Terminal Services.

To remove these mappings, remove the Scancode Map registry value and reboot.

Example 1

The following presents an example. To swap the left CTRL key with the CAPS LOCK key, use a registry editor (preferably Regedt32.exe) to modify the Scancode Map key with the following value:

00000000 00000000 03000000 3A001D00 1D003A00 00000000

The following table contains these entries broken into DWORD fields and the bytes swapped.
Value Interpretation
0x00000000 Header: Version. Set to all zeroes.
0x00000000 Header: Flags. Set to all zeroes.
0x00000003 Three entries in the map (including null entry).
0x001D003A Left CTRL key –> CAPS LOCK (0x1D –> 0x3A).
0x003A001D CAPS LOCK –> Left CTRL key (0x3A –> 0x1D).
0x00000000 Null terminator.

Facendo riferimento alla stringa del esempio: 00000000 00000000 03000000 3A001D00 1D003A00 00000000

03000000: numero di tasti da rimappare +1
Ho messo F6 esadecimale = 21 decimale perchè ho disabilitato 20 tasti i tasti F i tasti windows e i tasti CTRL, ALT e Home

3A001D00 due tasti 3A00 1D00 sharpkeys restituisce codici del tipo 00_1D quindi i due tasti presi ad esempio verrebbero restituiti da sharpkeys nella forma 00_1D e 00_3A se invece di rimappare il CTRL Left volessimo disabilitarlo la stringa sarebbe 0000 1D00 quindi prima in sequenza si mette l’effetto che il tasto deve produrre o un’altro tasto o un’altra azione e poi il tasto da rimappare.
Per manipolare la stringa ho utilizzano Notepad++, ho tolto gli spazi e in fine CTRL+f “Replace” in “Search Mode” Regular expression senza check matches newline
Find what: (..)
Replace with: 0x$1,

FreeCAD Macro MultiCut e MoveUp18mm

Trovato nel forum il seguente codice:

This example creates a parametric fusion object and make the referenced object its children

    shape=[]
    for i in Gui.Selection.getSelection():
        if i.isDerivedFrom("Part::Feature"):
            shape.append(i)

    App.ActiveDocument.addObject("Part::MultiFuse","Union").Shapes=shape
    App.ActiveDocument.recompute()

If you want to do it a bit more low-level you can do it this way:

    sel = Gui.Selection.getSelection()
    newShape = sel[0].Shape
    for i in sel[1:]:
        newShape = newShape.fuse(i.Shape)

    newObject = App.ActiveDocument.addObject("Part::Feature","myObject")
    newObject.Shape = newShape
    App.ActiveDocument.recompute()

 

MultiCut.FCMacro

 

Effettua la sottrazione di molteplici forme dalla forma selezionata per prima

Ho adattato il codice e commentato App.ActiveDocument.recompute() perchè inchioda l’elaborazione.

    import FreeCAD
    import Part

    sel = Gui.Selection.getSelection()
    newShape = sel[0].Shape
    for i in sel[1:]:
        newShape = newShape.cut(i.Shape)
    
    newObject = App.ActiveDocument.addObject("Part::Cut","MultiCut")
    newObject.Shape = newShape
    # App.ActiveDocument.recompute()

Utilizzo: selezionare per primo l’oggetto a cui si vogliono sottrarre gli altri oggetti selezionati ed eseguire la macro

 

MoveUp18mm.FCMacro

 

Effettua la copia di tutti gli oggetti selezionati e sposta tutti gli oggetti copiati più in alto di 18 mm

    import FreeCAD
    import Draft
    selection = FreeCADGui.Selection.getSelection()

    selection = FreeCADGui.Selection.getSelection()
    for i in selection:
      try:
    		Draft.move([i],FreeCAD.Vector(0.0,0.0,18.0),copy=True)
      except:
        continue

Utilizzo: selezionare tutti gli oggetti che si vogliono copiare spostati più in alto di 18mm (spostamento di 18mm sull’asse Z) ed eseguire la macro

FreeCAD Macro Copy Rotation 11.25 °

Prima prova di codice per FreeCAD

Le Macro in un sistema Windows iniziano con il path di dove si trovano # Macro Begin: C:\Users\%username%\AppData\Roaming\FreeCAD\MoveUp18mm.FCMacro, si può anche fare del semplice di testo salvato con l’estensione .FCMacro e collocarle nella giusta cartella %SystemDrive%\Users\%username%\AppData\Roaming\FreeCAD\. Le macro sono in Python.

CopyRotate.FCMacro

Effettua una copia ruotata dell’oggetto di 11,25° rispetto alla parametrizzazione degli assi definita nel codice.

import FreeCAD
import Draft

selection = FreeCADGui.Selection.getSelection()

for i in selection:

  try:

    Draft.rotate([i],11.25,FreeCAD.Vector(0.0,0.0,0.0),axis=FreeCAD.Vector(0.0,0.0,1.0),copy=True)

  except:

    continue

Utilizzo: selezionare l’oggetto che si intende ruotare e copiare ed eseguire la macro.