{"id":391136,"date":"2024-12-13T12:51:35","date_gmt":"2024-12-13T12:51:35","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=391136"},"modified":"2024-12-13T12:51:35","modified_gmt":"2024-12-13T12:51:35","slug":"gestisci-le-impostazioni-di-alimentazione-in-macos","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/gestisci-le-impostazioni-di-alimentazione-in-macos\/","title":{"rendered":"Gestire le impostazioni di alimentazione in macOS con uno script Bash personalizzato\u00a0"},"content":{"rendered":"<p>Una gestione efficiente dell&#8217;energia \u00e8 fondamentale per i professionisti IT e i <a href=\"https:\/\/www.ninjaone.com\/it\/cos-e-un-msp\">Managed Service Provider (MSP)<\/a> responsabili della manutenzione dei sistemi macOS. Questo script Bash personalizzato semplifica il processo di gestione delle <strong>impostazioni di alimentazione in macOS<\/strong>, consentendo agli utenti di regolare parametri come i timer di sospensione, la durata del timeout dello schermo e le funzioni di risparmio energetico. In questo articolo approfondiremo le funzionalit\u00e0, i casi d&#8217;uso e le implicazioni dell&#8217;utilizzo di questo script.<\/p>\n<h2>Comprendere la gestione delle impostazioni di alimentazione in macOS<\/h2>\n<p>Gestire le impostazioni di alimentazione in macOS garantisce ai sistemi un equilibrio tra prestazioni ed efficienza energetica, prolungando la durata della batteria e riducendo al minimo l&#8217;utilizzo di risorse non necessarie. Sebbene macOS fornisca strumenti nativi come il comando pmset, la configurazione manuale di queste impostazioni pu\u00f2 richiedere molto tempo ed essere soggetta a errori, soprattutto in ambienti con pi\u00f9 dispositivi. Questo script offre un approccio semplificato alla gestione delle impostazioni di alimentazione in macOS, fornendo un controllo granulare su vari parametri.<\/p>\n<h2>Lo script per gestire le impostazioni di alimentazione in macOS:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"bash\">#!\/usr\/bin\/env bash\r\n#\r\n# Description: Set Power and Sleep settings. It can adjust either the plugged-in or battery settings if requested. Please note, not all devices support all options.\r\n#   By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https:\/\/www.ninjaone.com\/terms-of-use.\r\n#   Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. \r\n#   Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. \r\n#   Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. \r\n#   Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. \r\n#   Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. \r\n#   Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. \r\n#   EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#\r\n# Preset Parameter: --powerSourceSetting \"Both\"\r\n#   Should these changes apply when the device is plugged in, on battery, or both?\r\n#\r\n# Preset Parameter: --screenTimeout \"10\"\r\n#\t\tTime in minutes to wait before turning off the screen. (0 to disable)\r\n#\r\n# Preset Parameter: --sleepTimeout \"10\"\r\n#\t\tTime in minutes to wait before the computer sleeps. (0 to disable)\r\n#\r\n# Preset Parameter: --diskTimeout \"10\"\r\n#\t\tTime in minutes for the disk to spin down when idle. (0 to disable)\r\n#\r\n# Preset Parameter: --powernap \"Disable\"\r\n#\t\tWhen the Mac goes to sleep, Power Nap activates periodically to update information such as Mail, Calendar, and other iCloud events.\r\n#\r\n# Preset Parameter: --terminalKeepAlive \"Enable\"\r\n#\t\tPrevents the system from going to sleep when a terminal session (like a remote login) is active, only allowing sleep if the session has been idle for too long.\r\n#\r\n# Preset Parameter: --dimOnBattery \"Enable\"\r\n#\t\tSlightly turn down the display brightness when switching to battery power.\r\n#\r\n# Preset Parameter: --lowPowerMode \"Enable\"\r\n#\t\tReduces energy consumption by lowering the system performance and brightness, stopping background processes, and adjusting system settings to extend battery life.\r\n#\r\n# Preset Parameter: --tcpKeepAlive \"Enable\"\r\n#\t\tEnsures that a network connection remains active by periodically sending keepalive packets to prevent the connection from being dropped due to inactivity.\r\n#\r\n# Preset Parameter: --wakeOnNetwork \"Only on Power Adapter\"\r\n#\t\tWake when an Ethernet magic packet is received.\r\n#\r\n# Preset Parameter: --help\r\n#\t\tDisplays some help text.\r\n#\r\n# Release Notes: Initial Release\r\n\r\n# Define initial argument variables with default values\r\n_arg_powerSourceSetting=\"Both\"\r\n_arg_screenTimeout=\r\n_arg_sleepTimeout=\r\n_arg_diskTimeout=\r\n_arg_powernap=\r\n_arg_terminalKeepAlive=\r\n_arg_dimOnBattery=\r\n_arg_wakeOneNetwork=\r\n_arg_lowPowerMode=\r\n_arg_tcpKeepAlive=\r\n\r\n# Function to display help menu\r\nprint_help() {\r\n  printf '\\n\\n%s\\n\\n' 'Usage: [--powerSourceSetting|-p &lt;arg&gt;] [--someSwitch|-s] [--help|-h]'\r\n  printf '%s\\n' 'Preset Parameter: --powerSourceSetting \"Both\"'\r\n  printf '\\t%s\\n' \"Should these changes apply when the device is plugged in, on battery, or both?\"\r\n  printf '%s\\n' 'Preset Parameter: --screenTimeout \"10\"'\r\n  printf '\\t%s\\n' \"Time in minutes to wait before turning off the screen. (0 to disable)\"\r\n  printf '%s\\n' 'Preset Parameter: --sleepTimeout \"10\"'\r\n  printf '\\t%s\\n' \"Time in minutes to wait before the computer sleeps. (0 to disable)\"\r\n  printf '%s\\n' 'Preset Parameter: --diskTimeout \"10\"'\r\n  printf '\\t%s\\n' \"Time in minutes for the disk to spin down when idle. (0 to disable)\"\r\n  printf '%s\\n' 'Preset Parameter: --powernap \"Disable\"'\r\n  printf '\\t%s\\n' \"When the Mac goes to sleep, Power Nap activates periodically to update information such as Mail, Calendar and other iCloud events.\"\r\n  printf '%s\\n' 'Preset Parameter: --terminalKeepAlive \"Enable\"'\r\n  printf '\\t%s\\n' \"Prevents the system from going to sleep when a terminal session (like a remote login) is active, only allowing sleep if the session has been idle for too long.\"\r\n  printf '%s\\n' 'Preset Parameter: --dimOnBattery \"Enable\"'\r\n  printf '\\t%s\\n' \"Slightly turn down the display brightness when switching to battery power.\"\r\n  printf '%s\\n' 'Preset Parameter: --lowPowerMode \"Enable\"'\r\n  printf '\\t%s\\n' \"Reduces energy consumption by lowering the system performance and brightness, stopping background processes, and adjusting system settings to extend battery life.\"\r\n  printf '%s\\n' 'Preset Parameter: --tcpKeepAlive \"Enable\"'\r\n  printf '\\t%s\\n' \"Ensures that a network connection remains active by periodically sending keepalive packets to prevent the connection from being dropped due to inactivity.\"\r\n  printf '%s\\n' 'Preset Parameter: --wakeOnNetwork \"Only on Power Adapter\"'\r\n  printf '\\t%s\\n' \"Wake when an Ethernet magic packet is received.\"\r\n  printf '\\n%s\\n' 'Preset Parameter: --help'\r\n  printf '\\t%s\\n' \"Displays this help menu.\"\r\n}\r\n\r\n# Function to display error message and exit the script\r\ndie() {\r\n  local _ret=\"${2:-1}\"\r\n  echo \"$1\" &gt;&amp;2\r\n  test \"${_PRINT_HELP:-no}\" = yes &amp;&amp; print_help &gt;&amp;2\r\n  exit \"${_ret}\"\r\n}\r\n\r\n# Function to parse command-line arguments\r\nparse_commandline() {\r\n  while test $# -gt 0; do\r\n    _key=\"$1\"\r\n    case \"$_key\" in\r\n    --powerSourceSetting | --powersourcesetting | --powersource)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_powerSourceSetting=$2\r\n      shift\r\n      ;;\r\n    --powerSourceSetting=*)\r\n      _arg_powerSourceSetting=\"${_key##--powerSourceSetting=}\"\r\n      ;;\r\n    --screenTimeout | --screentimeout | --screen)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_screenTimeout=$2\r\n      shift\r\n      ;;\r\n    --screenTimeout=*)\r\n      _arg_screenTimeout=\"${_key##--screenTimeout=}\"\r\n      ;;\r\n    --sleepTimeout | --sleeptimeout | --sleep)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_sleepTimeout=$2\r\n      shift\r\n      ;;\r\n    --sleepTimeout=*)\r\n      _arg_sleepTimeout=\"${_key##--sleepTimeout=}\"\r\n      ;;\r\n    --diskTimeout | --disktimeout | --disk)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_diskTimeout=$2\r\n      shift\r\n      ;;\r\n    --diskTimeout=*)\r\n      _arg_diskTimeout=\"${_key##--diskTimeout=}\"\r\n      ;;\r\n    --powernap | --powerNap)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_powernap=$2\r\n      shift\r\n      ;;\r\n    --powernap=*)\r\n      _arg_powernap=\"${_key##--powernap=}\"\r\n      ;;\r\n    --terminalKeepAlive | --terminalkeepawake | --terminalkeepalive)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_terminalKeepAlive=$2\r\n      shift\r\n      ;;\r\n    --terminalKeepAlive=*)\r\n      _arg_terminalKeepAlive=\"${_key##--terminalKeepAlive=}\"\r\n      ;;\r\n    --dimOnBattery | --dimonbattery | --dim)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_dimOnBattery=$2\r\n      shift\r\n      ;;\r\n    --dimOnBattery=*)\r\n      _arg_dimOnBattery=\"${_key##--dimOnBattery=}\"\r\n      ;;\r\n    --lowPowerMode | --lowpowermode | --lpm)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_lowPowerMode=$2\r\n      shift\r\n      ;;\r\n    --lowPowerMode=*)\r\n      _arg_lowPowerMode=\"${_key##--lowPowerMode=}\"\r\n      ;;\r\n    --tcpKeepAlive | --tcpkeepalive | --tcp)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_tcpKeepAlive=$2\r\n      shift\r\n      ;;\r\n    --tcpKeepAlive=*)\r\n      _arg_tcpKeepAlive=\"${_key##--tcpKeepAlive=}\"\r\n      ;;\r\n    --wakeOnNetwork | --wakeonnetwork | --won)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the optional argument '$_key'.\" 1\r\n      _arg_wakeOneNetwork=$2\r\n      shift\r\n      ;;\r\n    --wakeOnNetwork=*)\r\n      _arg_wakeOneNetwork=\"${_key##--wakeOnNetwork=}\"\r\n      ;;\r\n    --help | -h)\r\n      _PRINT_HELP=yes die 0\r\n      ;;\r\n    *)\r\n      _PRINT_HELP=yes die \"FATAL ERROR: Got an unexpected argument '$1'\"1\r\n      ;;\r\n    esac\r\n    shift\r\n  done\r\n}\r\n\r\n# Function to set power settings\r\nset_powersetting() {\r\n  while test $# -gt 0; do\r\n    local _key=\"$1\"\r\n    case \"$_key\" in\r\n    --setting)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the argument '$_key'.\"1\r\n      local _setting=$2\r\n      shift\r\n      ;;\r\n    --value)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the argument '$_key'.\"1\r\n      local _value=$2\r\n      shift\r\n      ;;\r\n    --errorMessage)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the argument '$_key'.\"1\r\n      local _errorMessage=$2\r\n      shift\r\n      ;;\r\n    --successMessage)\r\n      test $# -lt 2 &amp;&amp; die \"Missing value for the argument '$_key'.\"1\r\n      local _successMessage=$2\r\n      shift\r\n      ;;\r\n    --singleSetting)\r\n      local _singleSetting=\"on\"\r\n      ;;\r\n    *)\r\n      _PRINT_HELP=yes die \"FATAL ERROR: Got an unexpected argument '$1'\"1\r\n      ;;\r\n    esac\r\n    shift\r\n  done\r\n\r\n  # Check if required parameters are provided\r\n  if [[ -z $_setting || -z $_value || -z $_errorMessage || -z $_successMessage ]]; then\r\n    echo \"[Error] One of the required parameters was not provided.\" &gt;&amp;2\r\n    exit 1\r\n  fi\r\n\r\n  # Apply setting for \"Plugged In\" if applicable\r\n  if [[ ($_arg_powerSourceSetting == \"Both\" || $_arg_powerSourceSetting == \"Plugged In\") &amp;&amp; $_singleSetting != \"on\" ]]; then\r\n    pmset -c \"$_setting\" \"$_value\"\r\n  fi\r\n\r\n  # Apply setting for \"On Battery\" if applicable\r\n  if [[ ($_arg_powerSourceSetting == \"Both\" || $_arg_powerSourceSetting == \"On Battery\") &amp;&amp; $_singleSetting != \"on\" &amp;&amp; -n $batteryOptions ]]; then\r\n    pmset -b \"$_setting\" \"$_value\"\r\n  fi\r\n\r\n  # Apply setting for all power sources if single setting is enabled\r\n  if [[ $_singleSetting == \"on\" ]]; then\r\n    pmset -a \"$_setting\" \"$_value\"\r\n  fi\r\n\r\n  # Retrieve and verify the new value of the setting\r\n  newvalue=$(pmset -g custom | grep -w \"$_setting\")\r\n  if [[ -z $batteryOptions &amp;&amp; $_singleSetting != \"on\" ]]; then\r\n    newvalueAC=$(echo \"$newvalue\" | xargs | cut -f2 -d' ')\r\n  elif [[ $_singleSetting != \"on\" ]]; then\r\n    newvalueDC=$(echo \"$newvalue\" | xargs | cut -f2 -d' ')\r\n    newvalueAC=$(echo \"$newvalue\" | xargs | cut -f4 -d' ')\r\n  else\r\n    newvalue=$(echo \"$newvalue\" | xargs | cut -f2 -d' ')\r\n  fi\r\n\r\n  # Warn if unable to verify the setting change\r\n  if [[ -z $newvalue ]]; then\r\n    echo \"Warning: Unable to verify setting change for '$_setting'.\"\r\n  fi\r\n\r\n  # Check and report the new value for \"Plugged In\" setting\r\n  if [[ ($_arg_powerSourceSetting == \"Both\" || $_arg_powerSourceSetting == \"Plugged In\") &amp;&amp; $_singleSetting != \"on\" &amp;&amp; -n $newvalue ]]; then\r\n    if [[ $newvalueAC != \"$_value\" ]]; then\r\n      echo \"[Error] $_errorMessage on the 'Plugged In' Policy.\" &gt;&amp;2\r\n      EXITCODE=1\r\n    else\r\n      echo \"$_successMessage on the 'Plugged In' Policy.\"\r\n    fi\r\n  fi\r\n\r\n  # Check and report the new value for \"On Battery\" setting\r\n  if [[ ($_arg_powerSourceSetting == \"Both\" || $_arg_powerSourceSetting == \"On Battery\") &amp;&amp; $_singleSetting != \"on\" &amp;&amp; -n $newvalue &amp;&amp; -n $batteryOptions ]]; then\r\n    if [[ $newvalueDC != \"$_value\" ]]; then\r\n      echo \"[Error] $_errorMessage on the 'Battery' Policy.\" &gt;&amp;2\r\n      EXITCODE=1\r\n    else\r\n      echo \"$_successMessage on the 'Battery' Policy.\"\r\n    fi\r\n  fi\r\n\r\n  # Check and report the new value for single setting\r\n  if [[ $_singleSetting == \"on\" &amp;&amp; -n $newvalue ]]; then\r\n    if [[ $newvalue != \"$_value\" ]]; then\r\n      echo \"[Error] $_errorMessage\" &gt;&amp;2\r\n      EXITCODE=1\r\n    else\r\n      echo \"$_successMessage\"\r\n    fi\r\n  fi\r\n\r\n  echo \"\"\r\n}\r\n\r\n# Call the function to parse command-line arguments\r\nparse_commandline \"$@\"\r\n\r\n# If script form values are set, replace the command-line parameters with these values\r\nif [[ -n $powerSourceSetting ]]; then\r\n  _arg_powerSourceSetting=\"$powerSourceSetting\"\r\nfi\r\nif [[ -n $screenTimeoutInMinutes ]]; then\r\n  _arg_screenTimeout=\"$screenTimeoutInMinutes\"\r\nfi\r\nif [[ -n $sleepTimeoutInMinutes ]]; then\r\n  _arg_sleepTimeout=\"$sleepTimeoutInMinutes\"\r\nfi\r\nif [[ -n $diskTimeoutInMinutes ]]; then\r\n  _arg_diskTimeout=\"$diskTimeoutInMinutes\"\r\nfi\r\nif [[ -n $powerNap ]]; then\r\n  _arg_powernap=\"$powerNap\"\r\nfi\r\nif [[ -n $terminalKeepAlive ]]; then\r\n  _arg_terminalKeepAlive=\"$terminalKeepAlive\"\r\nfi\r\nif [[ -n $dimTheDisplayOnBattery ]]; then\r\n  _arg_dimOnBattery=\"$dimTheDisplayOnBattery\"\r\nfi\r\nif [[ -n $lowPowerMode ]]; then\r\n  _arg_lowPowerMode=\"$lowPowerMode\"\r\nfi\r\nif [[ -n $tcpKeepAlive ]]; then\r\n  _arg_tcpKeepAlive=\"$tcpKeepAlive\"\r\nfi\r\nif [[ -n $wakeOnNetwork ]]; then\r\n  _arg_wakeOneNetwork=\"$wakeOnNetwork\"\r\nfi\r\n\r\n# Check if the device has battery options available\r\nbatteryOptions=$(pmset -g custom | grep \"Battery Power\")\r\n\r\n# Validate the power source setting\r\nif [[ -z $_arg_powerSourceSetting || ($_arg_powerSourceSetting != \"Both\" &amp;&amp; $_arg_powerSourceSetting != \"Plugged In\" &amp;&amp; $_arg_powerSourceSetting != \"On Battery\") ]]; then\r\n  echo \"[Error] An invalid power source was given '$_arg_powerSourceSetting'. The only valid options are 'Both', 'Plugged In', and 'On Battery'.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\nif [[ -z $_arg_screenTimeout &amp;&amp; -z $_arg_sleepTimeout &amp;&amp; -z $_arg_diskTimeout &amp;&amp; -z $_arg_powernap &amp;&amp; -z $_arg_terminalKeepAlive &amp;&amp; -z $_arg_dimOnBattery &amp;&amp; -z $_arg_wakeOneNetwork &amp;&amp; -z $_arg_lowPowerMode &amp;&amp; -z $_arg_tcpKeepAlive ]]; then\r\n  PRINT_HELP=yes die \"[Error] No action given to take. Please specify a power setting to set.\" 1\r\nfi\r\n\r\n# Check if setting battery power source on a device without a battery\r\nif [[ $_arg_powerSourceSetting == \"On Battery\" &amp;&amp; -z $batteryOptions ]]; then\r\n  echo \"[Error] Cannot set battery power source setting on a device that does not have a battery.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Warn if trying to set battery power source on a device without a battery\r\nif [[ $_arg_powerSourceSetting == \"Both\" &amp;&amp; -z $batteryOptions ]]; then\r\n  echo \"[Warning] Cannot set battery power source setting on a device that does not have a battery. Ignoring battery power source settings.\"\r\nfi\r\n\r\n# Validate screen timeout argument\r\nif [[ -n $_arg_screenTimeout &amp;&amp; (! $_arg_screenTimeout =~ [0-9]+ || $_arg_screenTimeout -lt 0) ]]; then\r\n  echo \"[Error] An invalid screen timeout argument was given '$_arg_screenTimeout'. Please specify a positive number representing the desired timeout in minutes.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate sleep timeout argument\r\nif [[ -n $_arg_sleepTimeout &amp;&amp; (! $_arg_sleepTimeout =~ [0-9]+ || $_arg_sleepTimeout -lt 0) ]]; then\r\n  echo \"[Error] An invalid sleep timeout argument was given '$_arg_sleepTimeout'. Please specify a positive number representing the desired timeout in minutes.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate disk timeout argument\r\nif [[ -n $_arg_diskTimeout &amp;&amp; (! $_arg_diskTimeout =~ [0-9]+ || $_arg_diskTimeout -lt 0) ]]; then\r\n  echo \"[Error] An invalid disk timeout argument was given '$_arg_diskTimeout'. Please specify a positive number representing the desired timeout in minutes.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate powernap setting\r\nif [[ -n $_arg_powernap &amp;&amp; $_arg_powernap != \"Disable\" &amp;&amp; $_arg_powernap != \"Enable\" ]]; then\r\n  echo \"[Error] An invalid power nap setting was given '$_arg_powernap'. The only valid options are 'Disable' or 'Enable'.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate terminal keep alive setting\r\nif [[ -n $_arg_terminalKeepAlive &amp;&amp; $_arg_terminalKeepAlive != \"Disable\" &amp;&amp; $_arg_terminalKeepAlive != \"Enable\" ]]; then\r\n  echo \"[Error] An invalid terminal keep alive setting was given '$_arg_terminalKeepAlive'. The only valid options are 'Disable' or 'Enable'.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate dim on battery setting\r\nif [[ -n $_arg_dimOnBattery &amp;&amp; $_arg_dimOnBattery != \"Disable\" &amp;&amp; $_arg_dimOnBattery != \"Enable\" ]]; then\r\n  echo \"[Error] An invalid dim on battery setting was given '$_arg_dimOnBattery'. The only valid options are 'Disable' or 'Enable'.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate low power mode setting\r\nif [[ -n $_arg_lowPowerMode &amp;&amp; $_arg_lowPowerMode != \"Disable\" &amp;&amp; $_arg_lowPowerMode != \"Enable\" ]]; then\r\n  echo \"[Error] An invalid low power mode setting was given '$_arg_lowPowerMode'. The only valid options are 'Disable' or 'Enable'.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate TCP keep alive setting\r\nif [[ -n $_arg_tcpKeepAlive &amp;&amp; $_arg_tcpKeepAlive != \"Disable\" &amp;&amp; $_arg_tcpKeepAlive != \"Enable\" ]]; then\r\n  echo \"[Error] An invalid tcp keep alive setting was given '$_arg_tcpKeepAlive'. The only valid options are 'Disable' or 'Enable'.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Validate wake on network setting\r\nif [[ -n $_arg_wakeOneNetwork &amp;&amp; $_arg_wakeOneNetwork != \"Never\" &amp;&amp; $_arg_wakeOneNetwork != \"Always\" &amp;&amp; $_arg_wakeOneNetwork != \"Only on Power Adapter\" ]]; then\r\n  echo \"[Error] An invalid wake one network setting was given '$_arg_wakeOneNetwork'. The only valid options are 'Never', 'Always' and 'Only on Power Adapter'.\" &gt;&amp;2\r\n  exit 1\r\nfi\r\n\r\n# Set screen timeout if provided\r\nif [[ -n $_arg_screenTimeout ]]; then\r\n  timeoutError=\"Failed to set screen timeout of '$_arg_screenTimeout' minutes\"\r\n  timeoutSuccess=\"Successfully set screen timeout of '$_arg_screenTimeout' minutes\"\r\n\r\n  # Call the function to set the power setting for screen timeout\r\n  set_powersetting --setting \"displaysleep\" --value \"$_arg_screenTimeout\" --errorMessage \"$timeoutError\" --successMessage \"$timeoutSuccess\"\r\nfi\r\n\r\n# Set sleep timeout if provided\r\nif [[ -n $_arg_sleepTimeout ]]; then\r\n  sleepError=\"Failed to set sleep timeout of '$_arg_sleepTimeout' minutes\"\r\n  sleepSuccess=\"Successfully set sleep timeout of '$_arg_sleepTimeout' minutes\"\r\n\r\n  # Call the function to set the power setting for sleep timeout\r\n  set_powersetting --setting \"sleep\" --value \"$_arg_sleepTimeout\" --errorMessage \"$sleepError\" --successMessage \"$sleepSuccess\"\r\nfi\r\n\r\n# Set disk timeout if provided\r\nif [[ -n $_arg_diskTimeout ]]; then\r\n  diskError=\"Failed to set disk timeout of '$_arg_diskTimeout' minutes\"\r\n  diskSuccess=\"Successfully set disk timeout of '$_arg_diskTimeout' minutes\"\r\n\r\n  # Call the function to set the power setting for disk timeout\r\n  set_powersetting --setting \"disksleep\" --value \"$_arg_diskTimeout\" --errorMessage \"$diskError\" --successMessage \"$diskSuccess\"\r\nfi\r\n\r\n# Set power nap setting if provided\r\nif [[ -n $_arg_powernap ]]; then\r\n  if [[ $_arg_powernap == \"Enable\" ]]; then\r\n    _powernap_setting=1\r\n    napError=\"Failed to enable powernap\"\r\n    napSuccess=\"Successfully enabled powernap\"\r\n  else\r\n    _powernap_setting=0\r\n    napError=\"Failed to disable powernap\"\r\n    napSuccess=\"Successfully disabled powernap\"\r\n  fi\r\n\r\n  # Call the function to set the power setting for power nap\r\n  set_powersetting --setting \"powernap\" --value \"$_powernap_setting\" --errorMessage \"$napError\" --successMessage \"$napSuccess\"\r\nfi\r\n\r\n# Set terminal keep alive setting if provided\r\nif [[ -n $_arg_terminalKeepAlive ]]; then\r\n  if [[ $_arg_terminalKeepAlive == \"Enable\" ]]; then\r\n    _terminal_setting=1\r\n    terminalError=\"Failed to enable terminal keep alive\"\r\n    terminalSuccess=\"Successfully terminal keep alive\"\r\n  else\r\n    _terminal_setting=0\r\n    terminalError=\"Failed to disable terminal keep alive\"\r\n    terminalSuccess=\"Successfully disabled terminal keep alive\"\r\n  fi\r\n\r\n  # Call the function to set the power setting for terminal keep alive\r\n  set_powersetting --setting \"ttyskeepawake\" --value \"$_terminal_setting\" --errorMessage \"$terminalError\" --successMessage \"$terminalSuccess\"\r\nfi\r\n\r\n# Set the \"dim on battery\" setting if the argument is provided\r\nif [[ -n $_arg_dimOnBattery ]]; then\r\n  if [[ $_arg_dimOnBattery == \"Enable\" ]]; then\r\n    _dim_setting=1\r\n    dimError=\"Failed to enable the setting 'dim on battery'.\"\r\n    dimSuccess=\"Successfully enabled the setting 'dim on battery'.\"\r\n  else\r\n    _dim_setting=0\r\n    dimError=\"Failed to disable the setting 'dim on battery'.\"\r\n    dimSuccess=\"Successfully disabled the setting 'dim on battery'.\"\r\n  fi\r\n\r\n  # Call the function to set the power setting for dim on battery\r\n  set_powersetting --setting \"lessbright\" --value \"$_dim_setting\" --errorMessage \"$dimError\" --successMessage \"$dimSuccess\" --singleSetting\r\nfi\r\n\r\n# Set the low power mode setting if the argument is provided\r\nif [[ -n $_arg_lowPowerMode ]]; then\r\n  if [[ $_arg_lowPowerMode == \"Enable\" ]]; then\r\n    _lpm_setting=1\r\n    lpmError=\"Failed to enable low power mode\"\r\n    lpmSuccess=\"Successfully enabled low power mode\"\r\n  else\r\n    _lpm_setting=0\r\n    lpmError=\"Failed to disable low power mode\"\r\n    lpmSuccess=\"Successfully disabled low power mode\"\r\n  fi\r\n\r\n  # Call the function to set the power setting for low power mode\r\n  set_powersetting --setting \"lowpowermode\" --value \"$_lpm_setting\" --errorMessage \"$lpmError\" --successMessage \"$lpmSuccess\"\r\nfi\r\n\r\n# Set the TCP keep alive setting if the argument is provided\r\nif [[ -n $_arg_tcpKeepAlive ]]; then\r\n  if [[ $_arg_tcpKeepAlive == \"Enable\" ]]; then\r\n    _tcp_setting=1\r\n    tcpError=\"Failed to enable tcp keep alive\"\r\n    tcpSuccess=\"Successfully enabled tcp keep alive\"\r\n  else\r\n    _tcp_setting=0\r\n    tcpError=\"Failed to disable tcp keep alive\"\r\n    tcpSuccess=\"Successfully disabled tcp keep alive\"\r\n  fi\r\n\r\n  # Call the function to set the power setting for TCP keep alive\r\n  set_powersetting --setting \"tcpkeepalive\" --value \"$_tcp_setting\" --errorMessage \"$tcpError\" --successMessage \"$tcpSuccess\"\r\nfi\r\n\r\n# Set the wake on network setting if the argument is provided\r\nif [[ -n $_arg_wakeOneNetwork ]]; then\r\n  case $_arg_wakeOneNetwork in\r\n  \"Never\")\r\n    pmset -a womp 0\r\n    ;;\r\n  \"Always\")\r\n    pmset -a womp 1\r\n    ;;\r\n  \"Only on Power Adapter\")\r\n    if [[ -n $batteryOptions ]]; then\r\n      pmset -b womp 0\r\n    fi\r\n    pmset -c womp 1\r\n    ;;\r\n  esac\r\n\r\n  # Retrieve and verify the new value of the wake on network setting\r\n  newvalue=$(pmset -g custom | grep -w \"womp\")\r\n  if [[ -z $batteryOptions ]]; then\r\n    # Get the new value for the \"Plugged In\" policy if no battery options\r\n    newvalueAC=$(echo \"$newvalue\" | xargs | cut -f2 -d' ')\r\n  else\r\n    # Get the new values for both \"Battery\" and \"Plugged In\" policies\r\n    newvalueDC=$(echo \"$newvalue\" | xargs | cut -f2 -d' ')\r\n    newvalueAC=$(echo \"$newvalue\" | xargs | cut -f4 -d' ')\r\n  fi\r\n\r\n  # Check and report the new value for \"Always\" and \"Only on Power Adapter\" settings\r\n  if [[ $_arg_wakeOneNetwork == \"Always\" || $_arg_wakeOneNetwork == \"Only on Power Adapter\" ]]; then\r\n    if [[ $newvalueAC != 1 ]]; then\r\n      echo \"[Error] Unable to enable wake on network on the 'Plugged In' Policy.\" &gt;&amp;2\r\n      EXITCODE=1\r\n    else\r\n      echo \"Successfully enabled wake on network on the 'Plugged In' Policy.\"\r\n    fi\r\n  fi\r\n\r\n  # Check and report the new value for \"Never\" setting\r\n  if [[ $_arg_wakeOneNetwork == \"Never\" ]]; then\r\n    if [[ $newvalueAC != 0 ]]; then\r\n      echo \"[Error] Unable to disable wake on network on the 'Plugged In' Policy.\" &gt;&amp;2\r\n      EXITCODE=1\r\n    else\r\n      echo \"Successfully disabled wake on network on the 'Plugged In' Policy.\"\r\n    fi\r\n  fi\r\n\r\n  # Check and report the new value for \"Always\" setting on battery\r\n  if [[ -n $batteryOptions &amp;&amp; $_arg_wakeOneNetwork == \"Always\" ]]; then\r\n    if [[ $newvalueDC != 1 ]]; then\r\n      echo \"[Error] Unable to enable wake on network on the 'Battery' Policy.\" &gt;&amp;2\r\n      EXITCODE=1\r\n    else\r\n      echo \"Successfully enabled wake on network on the 'Battery' Policy.\"\r\n    fi\r\n  fi\r\n\r\n  # Check and report the new value for \"Never\" and \"Only on Power Adapter\" settings on battery\r\n  if [[ -n $batteryOptions &amp;&amp; ($_arg_wakeOneNetwork == \"Never\" || $_arg_wakeOneNetwork == \"Only on Power Adapter\") ]]; then\r\n    if [[ $newvalueDC != 0 ]]; then\r\n      echo \"[Error] Unable to disable wake on network on the 'Battery' Policy.\" &gt;&amp;2\r\n      EXITCODE=1\r\n    else\r\n      echo \"Successfully disabled wake on network on the 'Battery' Policy.\"\r\n    fi\r\n  fi\r\nfi\r\n\r\n# Exit the script with the set exit code if it is defined\r\nif [[ -n $EXITCODE ]]; then\r\n  exit \"$EXITCODE\"\r\nfi\r\n<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Risparmia tempo con gli oltre 300 script del Dojo NinjaOne.<\/p>\n<p>\u2192 <a class=\"waffle-rich-text-link\" href=\"https:\/\/www.ninjaone.com\/it\/prova-gratuita\/\">Accedi oggi stesso<\/a>.<\/p>\n<\/div>\n<h2>Cosa fa questo script per gestire le impostazioni di alimentazione in macOS<\/h2>\n<p>Questo script \u00e8 uno strumento completo per gestire le impostazioni di alimentazione in macOS. Supporta opzioni sia per la modalit\u00e0 a batteria che per quella con dispositivo collegato alla corrente, gestendo parametri quali:<\/p>\n<ul>\n<li><strong>Timeout dello schermo<\/strong>: Tempo prima che il display si spenga.<\/li>\n<li><strong>Timeout per la sospensione<\/strong>: Tempo prima che il sistema entri in modalit\u00e0 sospensione.<\/li>\n<li><strong>Spin-down del disco<\/strong>: Tempo prima che il disco si spenga durante l&#8217;inattivit\u00e0.<\/li>\n<li><strong>Power Nap<\/strong>: Aggiorna i dati del sistema durante la sospensione.<\/li>\n<li><strong>Modalit\u00e0 a basso consumo<\/strong>: Riduce il consumo di energia per prolungare la durata della batteria.<\/li>\n<li><strong>TCP Keepalive<\/strong>: Mantiene attive le connessioni di rete.<\/li>\n<li><strong>Wake on Network<\/strong>: Risveglia il dispositivo dalla sospensione alla ricezione di un pacchetto di rete.<\/li>\n<\/ul>\n<p>Lo script utilizza il comando pmset per configurare queste impostazioni, con una gestione degli errori e una verifica migliorate per garantire il successo dell&#8217;applicazione.<\/p>\n<h2>Come funziona lo script per gestire le impostazioni di alimentazione in macOS<\/h2>\n<h3>Parsing degli argomenti<\/h3>\n<p>Lo script per gestire le impostazioni di alimentazione in macOS accetta una serie di argomenti da riga di comando, come &#8211;screenTimeout, &#8211;sleepTimeout e &#8211;lowPowerMode. Ogni parametro pu\u00f2 essere personalizzato per applicare le impostazioni per l&#8217;alimentazione a batteria, per la modalit\u00e0 plug-in o per entrambe. Se vengono forniti argomenti errati o non validi, lo script mostra messaggi di errore dettagliati.<\/p>\n<h3>Convalida delle impostazioni in corso<\/h3>\n<p>Prima di applicare le modifiche, lo script per gestire le impostazioni di alimentazione in macOS convalida i valori di input per garantire la compatibilit\u00e0 con macOS. Per esempio:<\/p>\n<ul>\n<li>I valori di timeout dello schermo devono essere numeri interi non negativi.<\/li>\n<li>Le impostazioni di Power Nap possono essere solo &#8220;Abilita&#8221; o &#8220;Disabilita&#8221;.<\/li>\n<li>Il comportamento di Wake-on-network deve essere in linea con le funzionalit\u00e0 di macOS.<\/li>\n<\/ul>\n<h3>Caso d&#8217;uso ipotetico<\/h3>\n<p>Immagina un amministratore IT che gestisce un parco computer portatili macOS in un ambiente di livello enterprise. Vuole assicurarsi che:<\/p>\n<ul>\n<li>Gli schermi si spengano dopo 5 minuti di inattivit\u00e0 per risparmiare energia.<\/li>\n<li>I dispositivi entrino in modalit\u00e0 sleep dopo 10 minuti di funzionamento a batteria.<\/li>\n<li>Power Nap sia disattivato per risparmiare risorse durante le ore non lavorative.<\/li>\n<\/ul>\n<p>Usando questo script per gestire le impostazioni di alimentazione in macOS, pu\u00f2 farlo, garantendo la coerenza e riducendo i tempi di configurazione manuale.<\/p>\n<h2>Confronto tra lo script per gestire le impostazioni di alimentazione in macOS e altri metodi<\/h2>\n<p>Il comando pmset di macOS \u00e8 potente, ma richiede di essere inserito manualmente e non prevede meccanismi di convalida delle impostazioni. Gli strumenti basati su GUI, come Preferenze di sistema, offrono un&#8217;automazione limitata e non supportano la configurazione in blocco. Questo script per gestire le impostazioni di alimentazione in macOS rappresenta una soluzione ottimale combinando la flessibilit\u00e0 di pmset con la facilit\u00e0 dell&#8217;automazione.<\/p>\n<h2>Domande comuni sulla script per gestire le impostazioni di alimentazione in macOS<\/h2>\n<h3>Questo script per gestire le impostazioni di alimentazione in macOS pu\u00f2 funzionare su dispositivi senza batteria?<\/h3>\n<p>S\u00ec, ma le impostazioni specifiche della batteria saranno ignorate. Lo script per gestire le impostazioni di alimentazione in macOS rileva la disponibilit\u00e0 della batteria e genera avvisi se vengono utilizzate opzioni relative alla batteria su dispositivi che ne sono sprovvisti.<\/p>\n<h3>Cosa succede se fornisco argomenti non validi?<\/h3>\n<p>Lo script per gestire le impostazioni di alimentazione in macOS convalida tutti gli input e fornisce messaggi di errore dettagliati se un argomento non \u00e8 corretto.<\/p>\n<h3>\u00c8 sicuro usare Power Nap?<\/h3>\n<p>Power Nap pu\u00f2 consumare risorse aggiuntive durante la sospensione. Si consiglia di disattivarla negli ambienti che richiedono la massima efficienza energetica.<\/p>\n<h2>Implicazioni pi\u00f9 ampie per la sicurezza e l&#8217;efficienza IT<\/h2>\n<p>La gestione automatizzata dell&#8217;alimentazione contribuisce all&#8217;efficienza energetica e riduce le emissioni di carbonio, allineandosi agli obiettivi di sostenibilit\u00e0 aziendale. Inoltre, funzioni come la disabilitazione di Power Nap possono migliorare la sicurezza riducendo al minimo i processi in background e i potenziali vettori di attacco.<\/p>\n<h2>Best practice per l&#8217;utilizzo dello script<\/h2>\n<ol>\n<li><strong>Testa le configurazioni<\/strong>: Esegui lo script per gestire le impostazioni di alimentazione in macOS su un dispositivo di prova prima di distribuirlo per assicurarti che le impostazioni si comportino come previsto.<\/li>\n<li><strong>Documenta le modifiche<\/strong>: Conserva un registro delle impostazioni applicate per la risoluzione dei problemi e la conformit\u00e0.<\/li>\n<li><strong>Monitora le prestazioni<\/strong>: Verifica regolarmente che i dispositivi rispettino le impostazioni di alimentazione configurate.<\/li>\n<\/ol>\n<h2>Considerazioni finali<\/h2>\n<p>La gestione dell&#8217;alimentazione \u00e8 un aspetto critico dell&#8217;amministrazione dei sistemi macOS. Questo script semplifica il processo, consentendo ai professionisti IT di configurare e applicare in modo efficiente le impostazioni di alimentazione in macOS. Per gli MSP e le aziende che desiderano semplificare la gestione dei dispositivi macOS, soluzioni come <strong>NinjaOne<\/strong>\u00a0offrono strumenti avanzati di monitoraggio e automazione, garantendo che i dispositivi rimangano ottimizzati e sicuri.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4210],"use_cases":[4269],"class_list":["post-391136","script_hub","type-script_hub","status-publish","hentry","script_hub_category-macos"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/391136","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/comments?post=391136"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=391136"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=391136"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=391136"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}