Record

机会是留给有准备的人

利用appleScript切换网络位置

缘起:

每次从家里到公司,在mac上都要切换一下网络,切换过程比较繁琐,
于是动手写了个切换网络位置到applescript。

apple script 1

因使用的是dialog,只支持3个button,所以你只有二个网络位置时使用此脚本方便

tell application "System Events"
tell network preferences
    get the name of every location

    set allLocations to the name of every location
end tell
end tell

set allLocations to allLocations & {"cancel"}

display dialog "请选择当前的网络位置" buttons allLocations default button 3

set the button_pressed to the button returned of the result

if the button_pressed is not "cancel" then
tell application "System Events"
    tell network preferences
        do shell script "scselect '" & button_pressed & "'"

    end tell
end tell
else
beep

end if

apple script 2

因dialog只支持3个,所以写出下面支持多个网络位置的切换

tell application "System Events"
tell network preferences
    get the name of every location

    set allLocations to the name of every location
end tell
end tell

set chosen_network to choose from list allLocations

if the chosen_network is false then

else
tell application "System Events"
    tell network preferences
        do shell script "scselect '" & chosen_network & "'"
    end tell
end tell
end if

使用方式

1.保存代码格式是脚本,可以用命令启动:osascript scriptname(不推荐) 不推荐是因为,需要在命令行运行,打开命令行需要时间,
其实命令行你可以直接输入scselect home就可以切换了

2.保存代码格式为应用程序,直接双击运行,或结合alfred使用(推荐此方式)

注意

网络位置命名要英文,不然会有乱码异常