作为服务运行的 PowerShell 脚本行为异常

发布于 2024-08-20 18:27:39 字数 4303 浏览 6 评论 0原文

作为服务运行的 PowerShell 脚本行为异常

该项目: 创建一个后台进程来确定板载网卡是否已连接。如果已连接,请禁用无线网卡。当板载网卡未连接时,重新启用无线网卡。

为什么: 用户一直在热对接,获得奇怪的路由表或绑定到错误的 DNS 服务器。当他们尝试访问本地资源(例如打印机)时,他们无法访问,然后就在我的立方体中(他们会提交票证,但这也将是本地资源)。试图说服用户禁用自己的无线网络(通过笔记本电脑上的开关)或不使用热坞站,但效果有限。

问题: 下面的 PowerShell 脚本确实可以运行,并且在我的测试条件下可以正常工作。可能在大多数测试条件下,因为代码和 wmi 查询非常通用。手动运行脚本会产生预期的结果,但是通过我能找到的唯一方法 srvany.exe 将脚本作为服务运行,却产生了意外的结果并“破坏了东西”。

细节: 通过 srvany.exe 将脚本作为服务运行一次。当循环回来测试网络连接或尝试启用或禁用它的方法时。这些错误表明“get-wmiobject”不是正确的 Cmdlet。啊?它可以手动工作,可以工作一次,但禁用无线网卡后第二次就不行了。更糟糕的是,我的 shell 在服务之外突然无法执行 get-wmiobject,直到......直到您进入设备管理器并自行重新启用无线网卡。

调试尝试: 我重写了脚本并对其进行了一些清理,以使其能够获取 Do While 循环之外的对象。没有任何改变,但我保留了脚本,因为无论如何它看起来更干净。我在服务属性中启用了“与桌面交互”,果然您可以看到脚本尝试工作并出现前面提到的错误。 请帮忙。同样,这里的目标是运行一个后台进程,该进程在 Vista 或 7 中具有足够的权限来禁用和启用无线网卡。

#***********************************************************************
# "switch-wifi-srv.ps1"
# This script attempts  to identify if a wired network card is in use if
# one is, the Wireless network card is disabled, until the wired network
# card is no longer in use.
#
# Written by Aaron Wurthmann - aaron (AT) wurthmann (DOT) com
#
# 2010.02.10 ver 2 (Service Version)
# If you edit please keep my name or at the very least original author's.
# As of this writing I am unsure if script will work with all scenarios,
# however it has worked for me on Dell laptops running Windows 7 x64.
# -----------------------------------------------------------------------
# This script comes with ABSOLUTELY NO WARRANTY. 
# You may redistribute copies of the script under
# the terms of the GNU General Public License.
# -----------------------------------------------------------------------
# Service Installation:
# Aquire and install the Windows 2003 Resource Kit OR the srvany.exe.
# Use sc.exe and srvany.exe to create a service....
#   sc create SwitchWifiAuto binPath= "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe" DisplayName= "Switch Wifi Automatically"
# Edit registry entry for SwitchWifiAuto, add a key and a string value...
#   HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SwitchWifiAuto\Parameters]
#   "Application"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy RemoteSigned -File C:\\SwitchWifiAuto\\switch-wifi-srv.ps1"
#************************************************************************


$state=""
$wireStatus=""
$wifiStatus=""

# Get Wired and Wireless Card Objects
$objWire=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | Where-Object {$_.Name -notmatch "Wireless" -and $_.Name -notmatch "Virtual" -and $_.PhysicalAdapter -eq "True"} 
$objWifi=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | where-object {$_.Name -match "Wireless"}

# Get Name of Service to be Used in totally useless Do While Loop
$objService=get-service -display "Switch Wifi Automatically"

# Begin Do While Loop
Do {
#   Get status of wired network card. If enabled and connected set $state to Disable (which will later Disable the Wifi network card)
    [string]$wireStatus=$objWire | % {$_.NetEnabled}
    if($wireStatus -eq "True") {
        $state="Disable"
    }
#   Get Status of wireless card.
    if($objWifi){
        [string]$wifiStatus=$objWifi | % {$_.NetEnabled}
#       If $state is not set to disable and if the wireless card is currently disabled, enable it.
        if($state -ne "Disable") {
            if($wifiStatus -eq "False") {
                Out-Null -InputOject ($objWifi | % {$_.Enable()})
            }
#       If $state is set to Disable and if wireless card is currently enabled, disable it.
        } else {
            if($wifiStatus -eq "True") {
                Out-Null -InputOject ($objWifi | % {$_.Disable()})
            }
        }
    }

# Reset Checked Variables for good measure
$state=""
$wireStatus=""
$wifiStatus=""

# Sleep for 120 seconds (two minutes)
Start-Sleep -s 120

# Continuing looping (do while) until the service is not running.
# This is of course technically useless as when the service is not running neither is the script to check if the service is not running.
# I made it this way however because I don't like infinite loops and I thought it would be funny to it this way instead of while $var=0
} while ($objService.Status -eq "Running")

PowerShell Script Running as a Service Behaves Strangely

The Project:
Create a background process that determines if the on board network card is connected. If it is connected, disable the wireless network card. When the onboard network card is not connected, re-enable the wireless card.

Why:
Users hot-dock all the time, getting funky routing tables OR get bound to the wrong DNS servers. When they attempt to access a local resource, say printers, they aren’t able to and then are in my cube (they would file a ticket, but that too would be a local resource). Trying to convince users to disable their own wireless (via switch on laptop) or not hot dock has met with limited success.

The Problem:
The PowerShell script below does run, and does work under my testing conditions. Likely under most testing conditions as the code and wmi queries are pretty generic. Running the script manually yields the expected results, HOWEVER running the script as a service via the only method I could find, srvany.exe, yielded unexpected results and “broke stuff”.

Details:
Running the script as a service, via srvany.exe, works ONCE. When the loop comes back around to test the network connection or tries the method to enable or disable it. The errors indicate that “get-wmiobject” is not a proper Cmdlet. Huh? It works, manually, it works once, but a second time after it disabled the wireless network card it does not. Worse yet MY shell , outside of the service, suddenly can’t do a get-wmiobject, until…. until you go into Device Manager and re-enable the wireless network card yourself.

Debugging attempts:
I rewrote the script and cleaned it up a little to allow for it to get the objects outside of the Do While loop. Nothing changed, but I left the script that way as it seems cleaner anyhow. I enabled “Interact with Desktop” in the service properties and sure enough you can see the script trying to work and getting the before mentioned errors.
Please help. Again the object here is to run a background process, one with enough privileges in Vista or 7 to disable and enable the wireless network card.

#***********************************************************************
# "switch-wifi-srv.ps1"
# This script attempts  to identify if a wired network card is in use if
# one is, the Wireless network card is disabled, until the wired network
# card is no longer in use.
#
# Written by Aaron Wurthmann - aaron (AT) wurthmann (DOT) com
#
# 2010.02.10 ver 2 (Service Version)
# If you edit please keep my name or at the very least original author's.
# As of this writing I am unsure if script will work with all scenarios,
# however it has worked for me on Dell laptops running Windows 7 x64.
# -----------------------------------------------------------------------
# This script comes with ABSOLUTELY NO WARRANTY. 
# You may redistribute copies of the script under
# the terms of the GNU General Public License.
# -----------------------------------------------------------------------
# Service Installation:
# Aquire and install the Windows 2003 Resource Kit OR the srvany.exe.
# Use sc.exe and srvany.exe to create a service....
#   sc create SwitchWifiAuto binPath= "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe" DisplayName= "Switch Wifi Automatically"
# Edit registry entry for SwitchWifiAuto, add a key and a string value...
#   HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SwitchWifiAuto\Parameters]
#   "Application"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy RemoteSigned -File C:\\SwitchWifiAuto\\switch-wifi-srv.ps1"
#************************************************************************


$state=""
$wireStatus=""
$wifiStatus=""

# Get Wired and Wireless Card Objects
$objWire=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | Where-Object {$_.Name -notmatch "Wireless" -and $_.Name -notmatch "Virtual" -and $_.PhysicalAdapter -eq "True"} 
$objWifi=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | where-object {$_.Name -match "Wireless"}

# Get Name of Service to be Used in totally useless Do While Loop
$objService=get-service -display "Switch Wifi Automatically"

# Begin Do While Loop
Do {
#   Get status of wired network card. If enabled and connected set $state to Disable (which will later Disable the Wifi network card)
    [string]$wireStatus=$objWire | % {$_.NetEnabled}
    if($wireStatus -eq "True") {
        $state="Disable"
    }
#   Get Status of wireless card.
    if($objWifi){
        [string]$wifiStatus=$objWifi | % {$_.NetEnabled}
#       If $state is not set to disable and if the wireless card is currently disabled, enable it.
        if($state -ne "Disable") {
            if($wifiStatus -eq "False") {
                Out-Null -InputOject ($objWifi | % {$_.Enable()})
            }
#       If $state is set to Disable and if wireless card is currently enabled, disable it.
        } else {
            if($wifiStatus -eq "True") {
                Out-Null -InputOject ($objWifi | % {$_.Disable()})
            }
        }
    }

# Reset Checked Variables for good measure
$state=""
$wireStatus=""
$wifiStatus=""

# Sleep for 120 seconds (two minutes)
Start-Sleep -s 120

# Continuing looping (do while) until the service is not running.
# This is of course technically useless as when the service is not running neither is the script to check if the service is not running.
# I made it this way however because I don't like infinite loops and I thought it would be funny to it this way instead of while $var=0
} while ($objService.Status -eq "Running")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

披肩女神 2024-08-27 18:27:39

尝试删除任何输出。服务没有标准输出流。当缓冲区已满时,奇怪的事情就会发生。只是一个猜测(我从未使用过 powershell )。

Try to remove any output. Service don't have stdout stream. And when the buffer is full strange thing happens. Just a guess ( I never used powershell ).

面如桃花 2024-08-27 18:27:39

调试尝试:我重写了脚本并对其进行了一些清理
允许它获取 Do While 循环之外的对象。

您需要将这些包含在循环中,否则您将不会获得更新的值,并且循环将不执行任何操作。

Debugging attempts: I rewrote the script and cleaned it up a little to
allow for it to get the objects outside of the Do While loop.

You need to include these within the loop or you will not get updated values and the loop will do nothing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文