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

Connecting to EXOPSSession via Visual Basic Console Application

$
0
0

I successfully execute the following commands from the Windows PowerShell ISE on a 2008 R2 server.

Set-ExecutionPolicy RemoteSigned
$pw = convertto-securestring -AsPlainText -Force -String "Password"
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist "Login", $pw
$Session = New-EXOPSSession -ConnectionUri 'https://ps.compliance.protection.outlook.com/powershell-liveid' -Credential $cred
Import-PSSession $Session -AllowClobber -DisableNameChecking

However, when I execute these same commands on the same server from a .Net Console Application I receive the following error.

System.Management.Automation.CommandNotFoundException: The term 'New-EXOPSSession' 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 System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input) at System.Management.Automation.Runspaces.Pipeline.Invoke() at My.Module1.RunScript(String scriptText, String& ReturnCode)

Thanks,

Don


Errors in New-SMBShare Script

$
0
0

I'm trying to automate the preparation of Server Shares but I ran into a few errors. I'm reading the information from a INI file to form a Hashtable. The variable values are referenced from the Hashtable. Here is the code:

Get-Content -Path "C:\users\`$jstrode\Configuration2.ini" |
    foreach-object `
        -begin {
            # Create an Hashtable
            $hash=@{}
        } `
        -process {
            # Retrieve line with '=' and split them
            $key = [regex]::split($_,'=')
            if(($key[0].CompareTo("") -ne 0) -and ($key[0].StartsWith("[") -ne $True))
            {
                # Add the Key, Value into the Hashtable
                $hash.Add($key[0], $key[1])
            }
        } 

## Variables
$i = 0
$Server = ($hash.GetEnumerator() | Where-Object {$_.name -match "server$i"}).Value
$Path = ($hash.GetEnumerator() | Where-Object {$_.name -match "Path$i"}).Value
$ShareLocation = ((("\\{0}\{1}") -f $Server,$Path).replace(':','$')).replace(' ','')
$Share = ($hash.GetEnumerator() | Where-Object {$_.name -match "Share$i"}).Value 
$ShareRead = ($hash.GetEnumerator() | Where-Object {$_.name -match "Read$i"}).Value
$ShareModify = ($hash.GetEnumerator() | Where-Object {$_.name -match "Modify$i"}).Value
$ShareFullControl =  ($hash.GetEnumerator() | Where-Object {$_.name -match "FC$i"}).Value
$NTFS_Permissions = ("Nash\UTLPLN-NAS-PROD-RW","MODIFY","Allow");("Nash\UTLPLN-NAS-PROD-RO","READ","Allow")

#$Share = 'C_APPSTest2'
#$Path = 'C:\Test0\Test2'

## Create Folder
        IF (!(test-path $path))
                {
                    write-host "Creating folder: " $path -ForegroundColor green
                    New-Item -Path $path -ItemType directory
                } 
                else 
                {
                    write-host "The folder already exists: "$path -ForegroundColor Yellow
                }

## Create Share
    $Path
        IF (!(Get-SmbShare -Name $share -ErrorAction SilentlyContinue)) 
                {
                    write-host "Creating share: " $share -ForegroundColor green
                    New-SmbShare –Name $share –Path $path –Description ‘Test Shared Folder’ –FullAccess 'administrators' –ReadAccess 'Everyone','Nash\USWF-DEV-ANNEX-MASNAC' -ChangeAccess 'Authenticated Users'
                    
                } 
                else 
                {
                    write-host "The share already exists: " $share -ForegroundColor Yellow
                }

Output



 
Creating folder:   C:\Test0
New-Item : Cannot find drive. A drive with the name ' C' does not exist.
At line:35 char:21
+                     New-Item -Path $path -ItemType directory
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ( C:String) [New-Item], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemCommand

Creating share:   C_APPS
New-SmbShare : One or more parameter values passed to the method were invalid.
At line:47 char:21
+                     New-SmbShare –Name $share –Path $path –Descripti ...
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (MSFT_SMBShare:ROOT/Microsoft/Windows/SMB/MSFT_SMBShare) 

[New-SmbShare], CimException
    + FullyQualifiedErrorId : MI RESULT 4,New-SmbShare




When I put in discrete values it works like a charm. 

Get-Content -Path "C:\users\`$jstrode\Configuration2.ini" |
    foreach-object `
        -begin {
            # Create an Hashtable
            $hash=@{}
        } `
        -process {
            # Retrieve line with '=' and split them
            $key = [regex]::split($_,'=')
            if(($key[0].CompareTo("") -ne 0) -and ($key[0].StartsWith("[") -ne $True))
            {
                # Add the Key, Value into the Hashtable
                $hash.Add($key[0], $key[1])
            }
        } 

## Variables
$i = 0
$Server = ($hash.GetEnumerator() | Where-Object {$_.name -match "server$i"}).Value
$Path = ($hash.GetEnumerator() | Where-Object {$_.name -match "Path$i"}).Value
$ShareLocation = ((("\\{0}\{1}") -f $Server,$Path).replace(':','$')).replace(' ','')
$Share = ($hash.GetEnumerator() | Where-Object {$_.name -match "Share$i"}).Value 
$ShareRead = ($hash.GetEnumerator() | Where-Object {$_.name -match "Read$i"}).Value
$ShareModify = ($hash.GetEnumerator() | Where-Object {$_.name -match "Modify$i"}).Value
$ShareFullControl =  ($hash.GetEnumerator() | Where-Object {$_.name -match "FC$i"}).Value
$NTFS_Permissions = ("Nash\UTLPLN-NAS-PROD-RW","MODIFY","Allow");("Nash\UTLPLN-NAS-PROD-RO","READ","Allow")

#$Share = 'C_APPSTest2'
#$Path = 'C:\Test0\Test2'

## Create Folder
        IF (!(test-path C:\Test0))
                {
                    write-host "Creating folder: " C:\Test0 -ForegroundColor green
                    New-Item -Path C:\Test0 -ItemType directory
                } 
                else 
                {
                    write-host "The folder already exists: "C:\Test0 -ForegroundColor Yellow
                }

## Create Share
    
        IF (!(Get-SmbShare -Name C_APPS -ErrorAction SilentlyContinue)) 
                {
                    write-host "Creating share: " C_APPS -ForegroundColor green
                    New-SmbShare –Name C_APPS –Path C:\Test0 #–Description ‘Test Shared Folder’ –FullAccess 'administrators' –ReadAccess 'Everyone','Nash\USWF-DEV-ANNEX-MASNAC' -ChangeAccess 'Authenticated Users'
                    
                } 
                else 
                {
                    write-host "The share already exists: " C_APPS -ForegroundColor Yellow
                }

Nash\UTLPLN-NAS-PROD-RO
READ
Allow
The folder already exists:  C:\Test0
Creating share:  C_APPS

Name   ScopeName Path     Description
----   --------- ----     -----------
C_APPS *         C:\Test0

I'm puzzled why I am getting errors when the variables $Share and $Path expand to the proper values.

Add-Computer cmdlet does not prompt for password when running over SSH

$
0
0

Hello,

I need to join computer into domain. Add-Computer cmdlet does not prompt for password when I am running from text-based terminal. I am connected over SSH to remote computer. How can I force powershell/cmdlet to ask for password?

My steps:

1. I connect to remote computer over SSH (using Putty),
2. Then start powershell.exe in the terminal on remote computer,
3. Then run Add-Computer* cmdlet, but powershell does NOT prompt for domain admin password.

*Add-Computer -DomainName 'mydomain' -Credential adminlogin

When I connect through remote desktop and run the same cmdlet, it asks me for the password. I want the same behaviour when I am in pure text mode.

Thanks!

Extracting logs through Powershell using a script

$
0
0

Hello,

We have windows server 2012 R2.We want to create a task[we schedule it to run once every month] which can run in powershell and export result in xml file.

Can anyone help us out with the powershell script?


Get-ADUser Filter by Manager disabled

$
0
0

Hello All, 

I am trying to work on the Script to get the manager disabled for a specific set of accounts and i am using the following conditions to get the disabled manager information. 

Get-ADUser -Filter {(sAMAccountName -like "xx" -or sAMAccountName -like "yy")} -properties Manager|

Select Name,@{label="Manager Status";expression={(Get-ADUser $_.Manager -Properties SAMAccountName).SamAccountName}} |

Where-Object {($_.Manager).Enabled -eq $false} |Export-CSV C:\temp\managerdisable.csv


When i try to run this script i am getting a blank CSV file. 

New user script issues

$
0
0
Import-Module activeDirectory 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$Firstname = [Microsoft.VisualBasic.Interaction]::InputBox("Enter First Name", "Create New User")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$Lastname = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Lastname", "Create New User") | Out-Null
$title = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Job title ", "Create New User")| Out-Null
$email = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Job Email", "Create New User") | Out-Null
$department = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Job Department", "Create New User")| Out-Null
$street = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Street", "Create New User") | Out-Null
$city = [Microsoft.VisualBasic.Interaction]::InputBox("Enter City", "Create New User")| Out-Null
$postalcode = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Post Code", "Create New User")
$homephone = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Phone Number", "Create New User")
$PWD=[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$PWD= [Microsoft.VisualBasic.Interaction]::InputBox("Enter Password ", "Create New User")
$dnsroot = '@' + (Get-ADDomain).dnsroot
$Dname="$firstName " + "$LastName"
$UPN = Get-adforest | select UPNSuffixes -ExpandProperty UPNSuffixes | Out-GridView -PassThru | Select-Object -ExpandProperty UPNSuffixes
$company = "Test Company"
$ou = Get-ADOrganizationalUnit -Filter * | Select-Object -Property DistinguishedName | Out-GridView -PassThru | Select-Object -ExpandProperty DistinguishedName
New-ADUser -Name "$firstName $lastName" -Displayname $Dname -AccountPassword (ConvertTo-SecureString “$pwd” -AsPlainText -force) -GivenName $FirstName  -title $title -EmailAddress $email -Department $department -Company $Company -StreetAddress $street -city $city -PostalCode $postalcode -HomePhone $homephone -SamAccountName "$firstName.$lastName" -Surname $LastName  -UserPrincipalName "$firstName.$lastName@$UPN" -Path $OU -Enabled $TRUE
for ($i = 1; $i -le 100; $i++ )
{
    Write-Progress -Activity "User creation in Progress" -Status "$i% Complete:" -PercentComplete $i;
}
Write-Output "User $Firstname $lastName has been created"


send a file via email using a condition (Powershell Script)

$
0
0

as you show in the example below (CSVfile) i would like to send the PDF file using the path to the appropriate email, to 149 users automatically.
I like to know how I can do it using a powershell script

Email	                                  link
contoso1@***.com	           c:\\desktop\contoso1.pdf
contoso2@***.com	           c:\\desktop\contoso2.pdf

Best Reagards

Amir




Is it possible to do below steps in scripting ?

$
0
0

How to add Secure Email in Office 365

1.Open Outlook
2.Click on Create New in the Quick Steps box



3.Change the name to “Secure – New” (Note the name can be anything but it needs to be short to see it all)  Also click the drop down and select New Message and click Show Options

4. Add “[marked for secure delivery]” into the subject and click Finish

  

Script to List all users from groups which got access to a windows share

$
0
0

Can some one please help with a Script to List all users from groups which got access to a windows share

Thanks in advance

Shinz


Running script elevation in background

$
0
0
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
   {
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "DarkBlue"
   clear-host
   }
else
   {
   # We are not running "as Administrator" - so relaunch as administrator
   # Create a new process object that starts PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
   # Specify the current script path and name as a parameter
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
   # Exit from the current, unelevated, process
   exit
   }

# Run your code that needs to be elevated here
Get-AppXPackage -AllUsers -Name Microsoft.MicrosoftEdgeDevToolsPreview | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register “$($_.InstallLocation)\AppXManifest.xml” -Verbose}
Add-AppxPackage -register “C:\windows\SystemApps\Microsoft.MicrosoftEdgeDevToolsClient_8wekyb3d8bbwe\AppxManifest.xml” -DisableDevelopmentMode -Confirm:$false
Write-Host -NoNewLine "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

#Can I add  powershell.exe -nologo -command  in place of   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";


delete entire row from a column

$
0
0

Hi all friends,

there is a piece of code  tha is a pain in the neck.

I am trying to delete entire rows from an excel doc with powershell, but the code delete only some rows but not all.

the excel has the Sheet1 with three columns and the column A has some empty cells ( second sheet is to copy paste the values andd test again and again )

the code is this:

 

function Release-Ref ($ref) { ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( [System.__ComObject]$ref) -gt 0) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } $xlCellTypeLastCell = 11 $objExcel = new-object -comobject excel.application $objExcel.Visible = $True $objExcel.DisplayAlerts = $false $objWorkbook = $objExcel.Workbooks.Open('C:\Users\'+$env:USERNAME+'\Desktop\data.xlsx') $objWorksheet = $objWorkbook.Worksheets.Item('Sheet1') $a = $objWorksheet.Activate() $objRange = $objWorksheet.UsedRange $a = $objRange.SpecialCells($xlCellTypeLastCell).Activate() $intNewRow = $objExcel.ActiveCell.Row + 1 $strNewCell = "A" + $intNewRow Write-Host $strNewCell #------------------for each ------------------------------------------------------------------------------------ for ($i = 1; $i -le $intNewRow; $i++) { If ([string]::IsNullOrEmpty($objWorksheet.Cells.Item($i,1).value2)){ Write-Host "DELETING "$objWorksheet.Cells.Item($i, 1).Value2"Cell A"$i $Range = $objWorksheet.Cells.Item($i, 1).EntireRow $Range.Delete() $objWorkbook.Save() }else { Write-Host "NOT DELETING " $objWorksheet.Cells.Item($i, 1).Value2"Cell A"$i } } $objWorkbook.Save() $objWorkbook.Close() $objExcel.Quit() [gc]::collect() [gc]::WaitForPendingFinalizers()

excel template is here:

http s : / / drive google . c o m / open?id=1dTPgQN-gL_VqZXitzCusz5Or3quRt7Jz

could anyone help me to understand what the hell is happening please?

thanks , BR.



PowerShell Core on Linux Wait-Job timeout not working

$
0
0

Hi - 

I'm having trouble with the Wait-Job cmdlet on PowerShell Core for Linux. I have a Job created with Start-Job, which I wait for with:

Wait-Job $job -Timeout 30

Which should timeout after 30-seconds. However, the command consistently hangs for 2-minutes before it completes. Am I doing something wrong, and if not, could this bug be fixed? I'm running PowerShell 6.2.0 on Ubuntu 16.04.6 LTS.


Many thanks!

WMI command “ select Name and DeviceID from Win32_Volume” is giving same value for both Name and DeviceID for System Reserved Volume partition.

$
0
0

I am trying to get the details of all the partitions of one machine using WMI command. I need Name, Capacity and FreeSpace of each partitions, so used Win32_Volume command but this command is not giving appropriate Name for System Reserved Volume Partition. Name is coming as like this “ \?\Volume{0df78724-c412-11e4-80b4-806e6f6e6963}". it is same as DeviceID.

For all other partitions the Name value is proper. But how to get the appropriate human readable name for system Reserved volume.

Problem Launching PoweShell

$
0
0

Hay

I have Server 2016 standart.

When i open PS i get the attached screen and i cant run scripts, cmdlets etc.

Thanks

Mapping Service Accounts to Services without SPN mapping

$
0
0

Hello Team, 

I have a requirement where i would need to Map Windows Service Accounts to the Services they use when they logon to a particular application . We are basically trying to do a Clean up activity of the Service Accounts and not sure which service account uses what application within the infrastructure . 

Requirement 

65 Applications within the Infrastructure that needs to be mapped to the Service Accounts that uses it . I know i can pull out all the service accounts on power shell , The question is can i map these service accounts to the application services that they use ? 

Regards

K_Sundar


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!!!

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

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 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.com

Copy-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:\


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        7/17/2019   3:05 PM       41033728 Cube2.abf

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 ----------#

Viewing all 21975 articles
Browse latest View live


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