Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

How do you Import a file into a variable on Powershell

$
0
0
 Hello I have a question How can I Import a  file into a variable?

powershell command to get a list of users created in one month that belong to a specific group or not belong to the specific group.

$
0
0

Powershell command to get a list of users created in one month that belong to a specific group or not belong to the specific group.

script to find the PwdLastSet for the local admin on all servers

$
0
0

HI, does anyone know of a script or a way to find out the last time the local administrators password was reset on all servers?

thx

jason

Update powershell module Active Directory Windows 2008 r2

$
0
0
Is there a way to update the Active Directory powershell module for windows 2008 r2?  Update-module does not work because the Active Directory Module is not installed using the install-module cmdlet (at least thats what the error states).  I want to use the Get-adreplicationsubnet cmdlet but it is in AD ps module v3 and windows 2008 has AD ps module v1.  I am running a Windows update to see if that works.  Are there any other alternatives?

Using IF (Test-Connection) across multiple servers

$
0
0

I have multiple servers and clients I am trying to run this script against. I need to check the status of services and App Pools to make sure they are online. However the snag I am hitting is some client have 6 of the same server while others only have 1 or 2. This leads me with unncessary commands when running Test-Connection if a client only has 2 servers. 

What I am attempting to do is the following..

Test-Connection server 1 - If finds the server run code and move to server 2

Test Connection Server 2 - If finds the server run code and move to server 3

Test Connection Server 3 - If does not find then skip servers 4 5 and 6

It tends to hang on this section of the code due to the time it takes to check the servers. 

Previously they were all just separate blocks but I tried adding them under each others ScriptsBlocks however it only finds the first server and stops. Any help would be greatly appreciated.

#---------Mobility Server 1 ----------#
IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $MM1 -Quiet) {
Write-Host  -Foreground Green "Found Mobility Server $MM1"
Get-Service -ComputerName $MM1 -DisplayName *ServiceName* | Select-Object -Property DisplayName,MachineName,Status | Sort-object status|format-table -auto
Invoke-Command -ComputerName $MM1 -credential $credential -ScriptBlock {Import-Module WebAdministration
$webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$obj = New-Object PSObject -Property $item
$list += $obj}
$list | Format-Table -a -Property "WebAppName", "State", "UserIdentityType", "Username" | Write-Output

sleep 1
#---------Mobility Server 2 ----------#
  IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $MM2 -Quiet) {
  Write-Host  -Foreground Green "Found Mobility Server $MM2"
  Get-Service -ComputerName $MM2 -DisplayName *ServiceName* | Select-Object -Property DisplayName,MachineName,Status | Sort-object status|format-table -auto
  Invoke-Command -ComputerName $MM2 -credential $credential -ScriptBlock {
  Import-Module WebAdministration
$webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$obj = New-Object PSObject -Property $item
$list += $obj}
$list | Format-Table -a -Property "WebAppName", "State", "UserIdentityType", "Username" | Write-Output
sleep 1
#---------Mobility Server 3 ----------#
    IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $MM3 -Quiet) {
    Write-Host  -Foreground Green "Found Mobility Server $MM3"
    Get-Service -ComputerName $MM3 -DisplayName *ServiceName* | Select-Object -Property DisplayName,MachineName,Status | Sort-object status|format-table -auto
    Invoke-Command -ComputerName $MM3 -credential $credential -ScriptBlock 
    Import-Module WebAdministration
$webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$obj = New-Object PSObject -Property $item
$list += $obj}
$list | Format-Table -a -Property "WebAppName", "State", "UserIdentityType", "Username" | Write-Output
sleep 1
#---------Mobility Server 4 ----------#
      IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $MM4 -Quiet) {
      Write-Host  -Foreground Green "Found Mobility Server $MM4"
      Get-Service -ComputerName $MM4 -DisplayName *ServiceName* | Select-Object -Property DisplayName,MachineName,Status | Sort-object status|format-table -auto
      Invoke-Command -ComputerName $MM4 -credential $credential -ScriptBlock {
      Import-Module WebAdministration
$webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$obj = New-Object PSObject -Property $item
$list += $obj}
$list | Format-Table -a -Property "WebAppName", "State", "UserIdentityType", "Username" | Write-Output
sleep 1
#---------Mobility Server 5 ----------#
        IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $MM5 -Quiet) {
        Write-Host  -Foreground Green "Found Mobility Server $MM5"
        Get-Service -ComputerName $MM5 -DisplayName *ServiceName* | Select-Object -Property DisplayName,MachineName,Status | Sort-object status|format-table -auto
        Invoke-Command -ComputerName $MM5 -credential $credential -ScriptBlock {
        Import-Module WebAdministration
$webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$obj = New-Object PSObject -Property $item
$list += $obj}
$list | Format-Table -a -Property "WebAppName", "State", "UserIdentityType", "Username" | Write-Output
#---------Mobility Server 6 ----------#
          IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $MM6 -Quiet) {
          Write-Host  -Foreground Green "Found Mobility Server $MM6"
          Get-Service -ComputerName $MM6 -DisplayName *ServiceName* | Select-Object -Property DisplayName,MachineName,Status | Sort-object status|format-table -auto
          Invoke-Command -ComputerName $MM6 -credential $credential -ScriptBlock {
          Import-Module WebAdministration
$webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$obj = New-Object PSObject -Property $item
$list += $obj}
$list | Format-Table -a -Property "WebAppName", "State", "UserIdentityType", "Username" | Write-Output}}}}}}}}}}}
Else 
{Write-Host -Foregroundcolor Red "Mobility not found"
}

#---------End of Mobility Server Blocks ----------#

如何在powershell脚本(.ps1)中传递rename-computer的凭据?

$
0
0

大家好,

在的powershell脚本中,如何使用“重命名计算机”给出“-domaincredential”属性的密码?

没有像“-password”这样的属性/方法(例如图像)

我希望脚本静默执行,无需手动输入需要加密的密码

我参考以下链接,但我仍然对如何在.ps1脚本中完全编写它感受困惑
https://stackoverflow.com/questions/23482389/entering-a -password-for-domaincredential-in-rename-computer -in-powershell?noredirect = 1&lq = 1
https://stackoverflow.com/questions/13842611/how-to-pass-credentials-to-rename-command

我写了如下,但它不起作用(我已定义$ site,$ number和$ path)

$path=\\sc\cont
$computername="CN-D"+$number
$currentname=(Get-CimInstance -ClassName Win32_ComputerSystem).Name
$user="sc\joindomain"
$encpwd = Get-Content $path\password.bin
$passwd = ConvertTo-SecureString $encpwd
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $passwd
if($computername -ne $currentname){
    Rename-Computer -NewName $computername -DomainCredential $credential
}

先感谢您。


How can I pass the rename-computer credential in a powershell script (.ps1)?

$
0
0

Hello everyone,

How can i give the password to "rename-computer" for the "-domaincredential" attribute in the powershell script,?

There are no properties/methods like "-password" (eg image)

I want the script to execute silently, the without HAVING to Manually The Enter password that Needs to be encrypted.

I have read the links below,  but still confused How to Write the completely command in .ps1
: HTTPS: //stackoverflow.com/questions/23482389 /entering-a -password-for-domaincredential-in-rename-computer -in-powershell?Noredirect = 1&lq = 1
https://stackoverflow.com/questions/13842611/how-to-pass-credentials-to-rename- Command

I wrote the following, but it n't work to rename my computer name.

$path=\\sc\cont
$computername="CN-D"+$number
$currentname=(Get-CimInstance -ClassName Win32_ComputerSystem).Name
$user="sc\joindomain"
$encpwd = Get-Content $path\password.bin
$passwd = ConvertTo-SecureString $encpwd
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $passwd
if($computername -ne $currentname){
    Rename-Computer -NewName $computername -DomainCredential $credential
}

Thank you in advance.

RunSpace Double Ups

$
0
0

Hey I'm just getting into really using runspaces to gather information from the network to speed along the process but I'm noticing something intriguing with doubling up of information so I have a few questions about the script I'm using, in hopes you lovely people can help clarify things I'm clearly not understanding.

Apologies the script has gotten a little dirty as I'm trying to break it apart and test sections.

Question 1: the "$RunspacePool = [runspacefactory]::CreateRunspacePool(1,$breakdown)" would work out to say (1,4) variable my understanding is that should mean maximum threads of 4? however I notice the chunk is actually 5 threads, if I up the count its always 1 more and I'm not sure why.

Question 2: I noticed the last thread double ups on me if I were to run the below script against 20 PCs and expect results like:
Machine           Username           Disabled
Computer1       Administrator       Active
Computer1       Guest                  Disabled
Computer2       Administrator       Active
Computer2       Guest                  Disabled
Computer3       Administrator       Active
Computer3       Guest                  Disabled
Computer4       Administrator       Active
Computer4       Guest                  Disabled
Computer5       Administrator       Active
Computer5       Guest                  Disabled

but instead I'll get the results of:

Machine           Username            Disabled
Computer1       Administrator       Active
Computer1       Guest                  Disabled
Computer2       Administrator       Active
Computer2       Guest                  Disabled
Computer3       Administrator       Active
Computer3       Guest                  Disabled
Computer4       Administrator       Active
Computer4       Guest                  Disabled

Computer2       Administrator       Active
Computer2       Guest                  Disabled
Computer5       Administrator       Active
Computer5       Guest                  Disabled

noting that the last thread runs again on a previously used thread and has the previously collated data still within in it to return.  also thing to note when the script runs the next chunk despite the:

$jobs[$jobstart].PowerShell.Dispose()
$jobs[$jobstart].powershell = $null
$jobs[$jobstart].handle = $null

and
$jobs.clear()
$jobs = $null

lines let alone the $job variable being re declared I notice each thread is still retaining the previously returned information from prior jobs.  how can I clear this so the threads do not retain or return the previous information again without having to "unique" the results table after the fact.

Example Script:

$Computers = Get-ADComputer -Filter * -Properties lastLogonTimestamp, operatingsystem, servicePrincipalName | ?{$_.enabled -eq $true} | ?{($_.servicePrincipalName -join "-") -notlike "*clustervirtual*"}
$breakdown = [int]$env:NUMBER_OF_PROCESSORS
$runner = $Computers.Count
$num1 = 0
$num2 = $breakdown
$check = 0
$Results =$null
#region Runspace Pool
[runspacefactory]::CreateRunspacePool()
$SessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$RunspacePool = [runspacefactory]::CreateRunspacePool(1,$breakdown)
$PowerShell = [powershell]::Create()
$PowerShell.RunspacePool = $RunspacePool
$RunspacePool.Open()
#endregion

do{
    write-host "running block $num1..$num2 out of $runner" -ForegroundColor green
    $jobs = New-Object System.Collections.ArrayList
    $count = 1

    ForEach($Computer in $Computers[$num1..$num2]){
        $Parameters = @{
            Computer = $computer
            }
        $PowerShell = [powershell]::Create() 
        $PowerShell.RunspacePool = $RunspacePool
        [void]$PowerShell.AddScript({
            Param ($computer)
            run custom script
            return $Report
        })
        [void]$PowerShell.AddParameters($Parameters)
        $Handle = $PowerShell.BeginInvoke()
        $temp = '' | Select PowerShell,Handle
        $temp.PowerShell = $PowerShell
        $temp.handle = $Handle
        [void]$jobs.Add($Temp)   
    }
    $waittimer = 0
    do{
    if($jobs.handle.IsCompleted -like $false){
                                                    Write-Host "." -NoNewline
                                                    Start-Sleep -Seconds 1
                                                    $waittimer++}ELSE{$waittimer = 100}
    }until($waittimer -eq 100)
    $jobs = $jobs| ?{$_.handle.IsCompleted -like $true}
    $jobcount = $jobs.Count
    $jobstart = 0
    do{
        if($jobstart -lt $jobcount-1){
        $Results += $jobs[$jobstart].powershell.EndInvoke($jobs[$jobstart].handle)
        $jobs[$jobstart].PowerShell.Dispose()
        $jobs[$jobstart].powershell = $null
        $jobs[$jobstart].handle = $null
        }ELSE{
        $Results += $jobs[$jobstart].powershell.EndInvoke($jobs[$jobstart].handle) | ?{$_.machinename -like (($jobs[$jobstart].powershell.EndInvoke($jobs[$jobstart].handle) | select Machinename -Unique)[1]).machinename}
        $jobs[$jobstart].PowerShell.Dispose()
        $jobs[$jobstart].powershell = $null
        $jobs[$jobstart].handle = $null
        }
        $jobstart++
    }until($jobstart -eq $jobcount)
    $jobs.clear()
    $jobs = $null
    $num1 = $num1+$breakdown+1
    $num2 = $num2+$breakdown+1
    if($num2 -ge $runner){$num2 = $runner
    $check++}
    }until($check -gt 1)

$RunspacePool.Close()
New-TimeSpan -Start $start -End (get-date)


How do I remotely get-childitem?

$
0
0

Suppose i have a dev environment and prod environment

both of these environments have a shared drive: N:\however the FQDN of the shared drives differ between the environments

i.e.

dev: sharedserverdev.domain.com\data

prod: sharedserverprod.domain.com\data

now suppose i have the following servers on dev and prod

dev: server1.dev.domain.com

prod: server2.prod.domain.com

the N:drive shows up like this on server1 and server2

sharedd

i want to retrieve a file from the prod server2 N:drive to the dev server1 N: drive.

particularly, im interested in executing this command from dev server1.dev.domain.com:

$backupfile =Get-ChildItem"N:\" -Filter "*Cube2*.abf" | Sort-Object LastAccessTime -Descending | Select-Object -First 1

Restore-ASDatabase -Server "server3.dev.domain.com" -RestoreFile $backupfile -Name Cube1 -AllowOverwrite

the $backupfile is currently retrieved from the dev N: drive

which works and restores successfuly on target server (in this case server3.dev.domain.com)

however, i'd like to get a backup file from the prod N: drive. in thsi example, Cube2.abf file. i clearly can see the file exists there on prod N:\ drive

I am trying this answer here

$b =New-PSSession server2.prod.domain.comCopy-Item-FromSession $b N:\Cube2.abf -Destination N:\Cube2.abf

but i am getting error

Copy-Item : Cannot find path 'N:\Cube2.abf' because it does not exist.

ultimately, i dont even need to copy the file. i would just need to get it:

$backupfile =Invoke-Command-Cn"server2.prod.domain.com"{Get-ChildItem"N:\" -Filter "*Cube2*.abf" | Sort-Object LastAccessTime -Descending | Select-Object -First 1 }

but even THAT is not working either with Invoke-Command (whether running it from the prod server itself or dev server i am not getting any output except this error/warning (which from my experience is just a display line that doesnt really make a difference...). also, specifying a local drive thats not mounted, like D:\ or C:\ unlike N:\ still results in that error with Invoke-Command)

Attempting to perform the InitializeDefaultDrives operation on the 'FileSystem' provider failed.

if i run this command on the prod server

Get-ChildItem"N:\" -Filter "*Cube2*.abf" | Sort-Object LastAccessTime -Descending | Select-Object -First 1

i get output:

Directory: N:\ModeLastWriteTimeLengthName----------------------------a----7/17/20193:05 PM       41033728Cube2.abf

How to create a Powershell Script to run a sheduled task on WIndows 7 X64

$
0
0

Hi to all,

I would like to create a powrshell script that will exectute a scheduled task on Windows 7 X64.I tried to find it on Internet without solving my problems.Please find below the description of what i want.

Purpose: Create Powershell script to run a scheduled task
What does the scheduled task do? Execute the following command when starting the PC: 

Regsvr32 /s C:\Windows\SysWOW64\oleacc.dll

with the system account of the machine concerned.This task is performed when the PC is restarted.

i'm a beginner in powershell.

THank you for your help.

Regards,

Get BIOS time via powershell.

$
0
0
Is it possible to get the BIOS date and time via and powershell command? If, how? 

Conditional -WhatIf

$
0
0

Hi

I would like to apply the -WhatIf on my script when it runs on DEV/QA environments but not when it runs on PRD,

How can I have it in a sort of variable?

ex: something like Set-AdUSer -IDentity "xyz" Add @{aaa=bbb} $myWhatIfFlag

Thanks,

JD

 

How to regain focus on application

$
0
0

I have following code for PowerShell:

$wshell = New-Object -ComObject WScript.Shell;
$code = @'
    [DllImport("user32.dll")]
     public static extern IntPtr GetForegroundWindow();
'@
Add-Type $code -Name Utils -Namespace Win32
while (1 -eq 1) {
    Sleep 50; # Interval (in seconds) between switch 
    $wshell.AppActivate('Opera');
    $wshell.SendKeys('^{PGUP}'); # Ctrl + Page Up keyboard shortcut to switch tab
    $wshell.SendKeys('{F5}'); # F5 to refresh active page
    Start-Sleep -Milliseconds 100
    $wshell.AppActivate('chrome');
}

It is supposed to refresh and cycle Opera tabs every 50 sec and then regain focus on open app (where I was working). It is working nicely but I have it static for Chrome and I need to load open app and after refresh regain focus to open app.


PCSIDevice modules missing when running PS script from Visual Basic

$
0
0

Hi,

When running the PowerShell Get-Command from a Visual Basic program in a PowerShell runspace/pipeline, thePcsvDevice modules do not show up. When running the Get-Command from a normal PS box, these commands show up as expected. Is a solution available?

How to Fetch "Member of" groups from particular user ?

$
0
0

Hi All,

Good day.

Please help me by giving exact command for To Fetch "Member of" groups from particular AD user ? 

Thanks in Advance


Add "Full Control" to a Folder

$
0
0

I'm trying to add the "everyone" group to a folder (c:\test) and give to "Full Control".

What Powershell command would do this?

Also, I would like the NTFS permissions to be inherited by this folder (meaning: subfolders & files). 

I have looked all over the INTERNET, but I'm just not seeing the right answer.

This seems like it would be a simple thing to do.

Thanks,

List all folders in all drives with sizes

$
0
0

I need to report all folders from all fixed drives with their sizes. I need to include files list and sizes as long as they are in the root drive. Also to include hidden files/folders.

Can you show a link or script for this?

Thank you,

Learning and using PowerShell - docs first

$
0
0

I started off with "Select" and naming the individual properties to keep, but forgot about the "ExcludeProperties".

I don't feel picked on. Switching back and forth between Perl and Powershell, I tend to fall back on techniques from years gone by.


--- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

I was not really targeting you. I ws speaking in general to all who may stumble on this thread. I believe my statements are good for anyone trying to code and can be a reminder to all of us about the better approach to problem solving.

Read help.
Refer to the documentation repeatedly.
Search the web for good examples.
Lastly ask an informed question with  simple clear example.

Mostly the issue would be resolved by reading the help.  Unfortunately most new coders don't know how to use help so they ignore the best, first, source of answers.

The following should be the fist place anyone wishing to use PowerShell should type:

help help

Reading this carefully will save hundreds of future hours.

The first thing any tech (or Windows user) should learn to do is look for the help for anything.  Even notepad has help. 

Any professional programmer who fails to use help or to read the documentation will likely lose his job fairly quickly.

Of course asking the guy in the next cubical a simple reminder question like "What is the command for …?" is allowed but anything more detailed should be researched.  Research is what "professional technician" refers to.  Anyone who doesn't understand that is just a "wannabe".


\_(ツ)_/


Using Add-Member and Export-CSV with a foreach statement will not update a CSV file properly

$
0
0

Hi all,

I'm working on a part of a script that collects the Monitors and their respective Serial Numbers attached to a computer and export it to a CSV file. Since I won't know the number of monitors attached to every system, I am using a foreach statement to collect all the monitors.

The problem is the CSV file won't update correctly. If I run the script on a computer with one monitor, the CSV file will show "Monitor 1" and "Monitor 1 Serial Number". If I run the script on a computer with two monitors and have it output to the same CSV file, it will only show "Monitor 1" and "Monitor 1 Serial Number", however I am expecting it to add "Monitor 2" and "Monitor 2 Serial Number". Can anyone offer some suggestions? Here's my script so far:

# Get monitor info
$MonitorNumber = 0
$MonitorCounter1 = -3
$MonitorCounter2 = -2
$MonitorCounter3 = -1
$Monitors = Get-WmiObject -Namespace "root\WMI" -Class "WMIMonitorID"

function GetMonitorInfo {
  foreach ($Monitor in $Monitors) {
    ([System.Text.Encoding]::ASCII.GetString($Monitor.ManufacturerName)).Replace("$([char]0x0000)","")
    ([System.Text.Encoding]::ASCII.GetString($Monitor.UserFriendlyName)).Replace("$([char]0x0000)","")
    ([System.Text.Encoding]::ASCII.GetString($Monitor.SerialNumberID)).Replace("$([char]0x0000)","")

  }
}

# CSV properties
$infoObject = New-Object PSObject

foreach ($Monitor in $Monitors) {
  $MonitorNumber++
  $MonitorCounter1 = $MonitorCounter1 + 3
  $MonitorCounter2 = $MonitorCounter2 + 3
  $MonitorCounter3 = $MonitorCounter3 + 3
  $Monitor = GetMonitorInfo | Select-Object -Index $MonitorCounter1,$MonitorCounter2
  $MonitorSN = GetMonitorInfo | Select-Object -Index $MonitorCounter3
  $Monitor = $Monitor -join ' '
  Add-Member -InputObject $infoObject -MemberType NoteProperty -Name "Monitor $MonitorNumber" -Value $Monitor -Force
  Add-Member -InputObject $infoObject -MemberType NoteProperty -Name "Monitor $MonitorNumber Serial Number" -Value $MonitorSN -Force
}

$infoObject
$infoColl += $infoObject

# Export info to CSV file
try {
  $infoColl | Export-Csv -Path "$pwd\Monitors.csv" -NoTypeInformation -Append -Force
  Write-Host -ForegroundColor Green "Inventory was successfully updated!"
  exit 0
}
catch {
}
throw "Unable to export to the CSV file. Please check the permissions on the file."

Thank you!!!

Code to change TCP port for SQL works locally but not remotely

$
0
0

Hi All.

I have the piece of code below, which works fine when run locally however when run using PowerShell remoting/credssp, it comes up with an error.

$MachineObject = new-object ('Microsoft.SqlServer.Management.Smo.WMI.ManagedComputer') 
$ProtocolUri = "ManagedComputer[@Name='" + (get-item env:computername).Value + "']/ServerInstance[@Name='DEV01']/ServerProtocol"
$tcp = $MachineObject.getsmoobject($ProtocolUri + "[@Name='Tcp']")
$np = $MachineObject.getsmoobject($ProtocolUri + "[@Name='Np']")
$sm = $MachineObject.getsmoobject($ProtocolUri + "[@Name='Sm']")
$MachineObject.getsmoobject($tcp.urn.Value + "/IPAddress[@Name='IPAll']").IPAddressProperties[1].Value = "2222"
$tcp.alter()


$service_name = 'MSSQL$DEV01'
$service = Get-Service -Name $service_name -ErrorAction SilentlyContinue
  if ($service.Length -gt 0){
        Write-host "Restarting the service - $service_name"
        Restart-Service -Name 'MSSQL$DEV01' -Force 
        Start-Sleep -s 10
  }

When executed from a remote host, I get the error.

Exception calling "GetSmoObject" with "1" argument(s): "Attempt to retrieve data for object failed for ManagedComputer 'MY-Server_Name."

Any help or explanation of what could be causing this would be appreciated.

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>