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

How to reboot multiple servers one by one using time frame of 5 min and check the services after reboot.

$
0
0

Hello,

I want a sample script for rebooting multiple servers one by one using time frame of 5min.

Like 

Server A reboot and wait for 5 min / Server A up and check the services in the server that should be up and go for next server B.

Please help.


Getting service state and starting it

$
0
0

Hello,

I want to get service state, and if the service is not started then start it, and repeat the process until it really starts (it may fail sometimes).

I tried the following :
     $svc = Get-Service Service_Name
     while ($svc.Status -eq "Stopped") {Start-Service $svc.name}
But here $svc remains static, then it won't exit the while loop even is service is started.

So I tried this in order to query the service at each occurence of loop:
     while ((get-service Service_Name | $_.Status) -eq "Stopped") {Start-service Service_Name}
But I get syntax error.

What is the correct syntax ?

Thanks for your help !
Regards
Julien

Powershell loop through to set variable from each line of text file

$
0
0

I am trying to write a PowerShell script which calls an API which gets a list of machine names from the API. It then puts the machine names in a txt file where I then remove all the unwanted characters from the file just leaving me with lines of the server names. I then want to take each line, set it a variable and then use it to call another API function. I am having issues with selecting the line calling the function and then it continuing to loop through setting each line as the variable and running the API call.

Any help appreciated. 

# Mute  hosts
#Variables
$api_key =
$app_key =
$query =
$http_method =
$url_signature =
$ddhostfile =
$specialCharacter = "["
$specialCharacter1 = "]"

#Call to DDOG
$url_base = "https://app.datadoghq.com/"
$url = $url_base + $url_signature + "?api_key=$api_key" + "&" + "application_key=$app_key"+ "&" + "q=$query"
$http_request = New-Object -ComObject Msxml2.XMLHTTP
$http_request.open($http_method, $url, $false)
$http_request.setRequestHeader("Content-type", "application/json")
$http_request.setRequestHeader("Connection", "close")
$http_request.send($parameters)
$http_request.status
$http_request.responseText -split ", " | Out-File $ddhostfile

#Remove unwanted text from results
(gc $ddhostfile | select -Skip 1) | sc $ddhostfile
(gc $ddhostfile) | ForEach-Object { $_ -replace 'hosts' } > $ddhostfile
(gc $ddhostfile) | ForEach-Object { $_ -replace ':' } > $ddhostfile
(gc $ddhostfile) | ForEach-Object { $_ -replace [regex]::Escape($specialCharacter) } > $ddhostfile
(gc $ddhostfile) | ForEach-Object { $_ -replace '"' } > $ddhostfile
(gc $ddhostfile) | ForEach-Object { $_ -replace [regex]::Escape($specialCharacter1) } > $ddhostfile
(gc $ddhostfile) | ForEach-Object { $_ -replace '}' } > $ddhostfile
(gc $ddhostfile) | ForEach-Object { $_ -replace ' ' } > $ddhostfile

#loop through machine names and set as variable to call API function
foreach ($line in $ddhostfile)
{
$ddhost = (gc $ddhostfile) | select -Index 1
write-host $ddhost
$url = "https://app.datadoghq.com/api/v1/host/$ddhost/mute?api_key=&application_key=
write-host $url
Invoke-WebRequest -Method POST -Uri $url
}

Thanks

Need Batch Script to Know Server Details like SystemName,caption,freespace,size,System date in single file

$
0
0

Hi ,

I want to generate file through Batch Script.

File should contain Servername,Caption(Drive name),Freespace,Totalspace(size),Systemdate.

Please share script on same, if any one have idea on that......

Thanks&Regards,

Bala


Creating a custom input box for a custom powershell script.

$
0
0

Hi All,

A very good day.

I have a custom made powershell script for one of our monitoring tool.

The script imports the Module and then using a input file (List of servers) it will fetch them and Silence / Snooze / Put it in Maintenance mode for a specific time.

=============================

                     

Import-Module Operationsmanager
$path = "C:\Users\amgravi\Desktop\MM"
$MyFile = Get-content "$path\list.txt" 
foreach($srv in $MyFile) 
    { 
    Write-host "ServerName : $srv" 

    $startTime = [DateTime]::Now 
    $endTime = $startTime.AddMinutes(10) 


    $srv += "*" 
    $Class = get-SCOMclass | where-object {$_.Name -eq "Microsoft.Windows.Computer"}; 
    $Instance = Get-SCOMClassInstance -Class $Class | Where-Object {$_.Displayname -Like "$srv"}; 
    Start-SCOMMaintenanceMode -Instance $Instance -Reason "PlannedOther" -EndTime $endTime -Comment "Scheduled SCOM Maintenance Window" 


    }

===============

$endTime = $startTime.AddMinutes(10)  here the number 10 defines that the servers have to be Silence / Snooze / Put it in Maintenance mode for 10 minutes.

I am trying to create a GUI Box for this function where when a user tries to run this script manually it should ask him for the number of minutes and then based on the user input it should do it rather than a user manually opening the script and entering the duration.

I got a script from a forum for a ping commandlet via GUI which will ask for the server name and perform the ping function:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  

$Form = New-Object System.Windows.Forms.Form    
$Form.Size = New-Object System.Drawing.Size(600,400)  

############################################## Start functions

function pingInfo {
$wks=$InputBox.text;
$pingResult=ping $wks | fl | out-string;
$outputBox.text=$pingResult
                     } #end pingInfo

############################################## end functions

############################################## Start text fields

$InputBox = New-Object System.Windows.Forms.TextBox 
$InputBox.Location = New-Object System.Drawing.Size(20,50) 
$InputBox.Size = New-Object System.Drawing.Size(150,20) 
$Form.Controls.Add($InputBox) 

$outputBox = New-Object System.Windows.Forms.TextBox 
$outputBox.Location = New-Object System.Drawing.Size(10,150) 
$outputBox.Size = New-Object System.Drawing.Size(565,200) 
$outputBox.MultiLine = $True 
$outputBox.ScrollBars = "Vertical" 
$Form.Controls.Add($outputBox) 

############################################## end text fields

############################################## Start buttons

$Button = New-Object System.Windows.Forms.Button 
$Button.Location = New-Object System.Drawing.Size(400,30) 
$Button.Size = New-Object System.Drawing.Size(110,80) 
$Button.Text = "Ping" 
$Button.Add_Click({pingInfo}) 
$Form.Controls.Add($Button) 

############################################## end buttons

$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()

=====================================

But i am not sure on how to use this for my script just for adding it to the $endTime = $startTime.AddMinutes(10)  function.

Can any one help me on this.


Gautam.75801



Send-MailMessage with German TypeFace

$
0
0

I am stumped, I am trying to a mail via Powershell, as below, all works as it should but I have a problem with the German Letters showing up as ? for eample:

$To ='Email'
$From='AnotherEmail'
$MessageSubject = "Subject Blah Blah"
$MessageBody =  " Blah Blah Grüß Blah "

Send-MailMessage -From $From -Subject $MessageSubject -To $To -Body  $MessageBody   -BodyAsHtml -Priority High -SmtpServer "Servername"

This will show up as

                    Blah Blah Gr?? Blah

has anyone got around this problem ?

Thanks

Running batch file in remote machine

$
0
0

HI, 

Lets say i am in machine1. I want to execute a batch file which is in machine2, so that notepad.exe will be executed and a notepad will be opened onmachine2 

How can i do this using powershell script.


sekhar

Foreach loop when querying for logged on users

$
0
0

Hi Guys

Having an issue with a script I wrote. $status should basically change to "loggedon" when user is logged on to the server.
The function "Get-LoggedOnUsers" works and returns the following:

UserName     : suppadmin
ComputerName : localhost
SessionName  :
Id           : 2
State        : Disc
IdleTime     : 19:13
LogonTime    : 22/07/2016 10:46
Error        :

UserName     : webmin
ComputerName : localhost
SessionName  : rdp-tcp#0
Id           : 3
State        : Active
IdleTime     : .
LogonTime    : 27/07/2016 18:35
Error        :

If I run the script and query the $User variable of the script it does not return anything.
I am a beginner in PowerShell so sorry in advanced in case this is a stupid mistake :-)

Thanks,
Michael

function Get-LoggedOnUsers {
param(
    [CmdletBinding()]
    [Parameter(ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true)]
    [string[]]$ComputerName = 'localhost'
)
begin {
    $ErrorActionPreference = 'Stop'
}

process {
    foreach ($Computer in $ComputerName) {
        try {
            quser /server:$Computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {
                $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
                $HashProps = @{
                    UserName = $CurrentLine[0]
                    ComputerName = $Computer
                }

                # If session is disconnected different fields will be selected
                if ($CurrentLine[2] -eq 'Disc') {
                        $HashProps.SessionName = $null
                        $HashProps.Id = $CurrentLine[1]
                        $HashProps.State = $CurrentLine[2]
                        $HashProps.IdleTime = $CurrentLine[3]
                        $HashProps.LogonTime = $CurrentLine[4..6] -join ' '
                        $HashProps.LogonTime = $CurrentLine[4..($CurrentLine.GetUpperBound(0))] -join ' '
                } else {
                        $HashProps.SessionName = $CurrentLine[1]
                        $HashProps.Id = $CurrentLine[2]
                        $HashProps.State = $CurrentLine[3]
                        $HashProps.IdleTime = $CurrentLine[4]
                        $HashProps.LogonTime = $CurrentLine[5..($CurrentLine.GetUpperBound(0))] -join ' '
                }

                New-Object -TypeName PSCustomObject -Property $HashProps |
                Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
            }
        } catch {
            New-Object -TypeName PSCustomObject -Property @{
                ComputerName = $Computer
                Error = $_.Exception.Message
            } | Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
        }
    }
}}

$usertocheck = "webmin"
$LoggedonUsers = Get-LoggedOnUsers
$status = "test"

foreach ($User in $LoggedonUsers.UserName){
    if ($User -eq $usertocheck){
    $status = "loggedon"
       }
    }

PS: Just in case anyone wonders the part of the function is from the script gallery and not my own work :-) Just google Get-LoggedOnUser.ps1 and it should guide you to the download page. Really great script by the way!


IIS SSLBinding remove-item : Illegal characters in path.

$
0
0

Hi, I have a SSL binding in IIS with a wild char (*.test.com), how can I remove it with powershell? Because the following command doesn't work:

get-childitem IIS:\SslBindings\ | remove-item

It throws the following exception:

remove-item : Illegal characters in path.
At line:1 char:35+ get-childitem IIS:\SslBindings\ | remove-item+                                   ~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (\\DESKTOP-54RFN...*.test.com:String) [Remove-Item], ArgumentException+ FullyQualifiedErrorId : IllegalPath,Microsoft.PowerShell.Commands.RemoveItemCommand

ERROR:Cannot process argument transformation on parameter 'DriveLetter'. Cannot convert value "$DriveLetter" to type "System.Char". Error: "String must be exactly one character long."

$
0
0

Hi All,

I created a script for formatting the drive and assigning the drive label on remote servers. It works fine if I manually change the details. But when trying to import the values from a CSV input its throwing the error mentioned below.

Error:

Cannot process argument transformation on parameter 'DriveLetter'. Cannot convert value "$DriveLetter" to type "System.Char". Error: "String must be exactly one character long."
    + CategoryInfo          : InvalidData: (:) [New-Partition], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,New-Partition
    + PSComputerName        : 123Remote server


*************************************************************

CSV input :

DiskNumber    DriveLetter    NewFileSystemLabel    AllocationUnitSize
    7            N            Drive_N                4096

*************************************************************

My Script:

# New Partation/Drive letter/Farmat/Lable/Allocation

Measure-Command{
Clear

$Data = Import-csv 'C:\Users\U142008\Desktop\Storage_Data_Input.csv'
    $DiskNumber=$Data.DiskNumber
        $DriveLetter=$Data.DriveLetter
            $NewFileSystemLabel=$Data.NewFileSystemLabel
                $AllocationUnitSize=$Data.AllocationUnitSize

#$c=Get-Credential Admin
    $ServerList = Get-Content 'H:\My Documents\My Powershell\serverlist.txt'
        foreach ($ServerName in $ServerList){
            Invoke-Command -ComputerName $ServerName -Credential $c -ScriptBlock {
            
# New Partation/Drive letter/Farmat/Lable/Allocation
    Stop-Service -Name ShellHWDetection
        New-Partition -DiskNumber "$DiskNumber" -UseMaximumSize -DriveLetter '$DriveLetter' |             Format-Volume -FileSystem NTFS -NewFileSystemLabel "$NewFileSystemLabel" -AllocationUnitSize "$AllocationUnitSize" -Force -Confirm:$false
     
    Start-Service -Name ShellHWDetection
}}}

Powershell Stop-Service

$
0
0
Is there a way to stop a service and not wait until it's done? I have services that take several minutes to stop and when doing these sequentially it takes a long time to get them all to stop. 

Uninstalling Programs Using Powershell running from GPO Start up, Win7

$
0
0

I'm Trying to uninstall a program from every PC at a specific location around 100 computers.This is the powershell Script that i'm using:


$app = Get-WmiObject -Class Win32_Product | Where-Object {
    $_.Name -match "Program Trying to Uninstall"
}

$app.Uninstall()


I want this script to run on start up using GPO.

Mine is running from 'Computer Configuration' > 'Policies' > 'Windows Settings' > 'Scripts (Startup/ShutDown)' > PowerShell Scripts

I have the 'Run Windows PowerShell scripts first' drop down selected.

The script is in the policies default folder with the correct permisions.

It runs fine on my Windows 10 machines but fails on the Win 7 Machines.

Help!!!! I just can't find the reason why????????








Mount SP Content database Error

$
0
0

Hello world! I am trying to mount a content database, unfortunately I am getting this crazy message.

"Invalid Object name 'Sites'

the funny thing is im not referencing any site, here is my code:

Mount-SPContentDatabase-NameSP_Content Database-WebApplicationhttp://mysitename -DatabaseServersp-dbdev

Powershell Question

$
0
0
If I double click a .ps1 file from my desktop to open with powershell how can I get the application to stay open so I can read the error message. 

Compare two files and replace string in one of them

$
0
0

Hi,

I'm looking for solution to replace one string from one file with string from other file.

Let's say I've two txt files:

file1:

serial_1 serialN1
serial_2 serialN2

file2:

something serial_3 serialN1
something serial_4 serialN2

What I would like to get is replace serial_3 with serial_1 and serial_4 with serial_2.
So I would like to search file2 with numbers from second column (serialN) from file1 and replace "leading" serial number in file2 when serialN match entry from first file.

What i have so far:

$source = Get-Content file1
foreach ($line in $source){
$position_source = ($line.Split())[1]
$serial_source = ($line.split())[0]
$destination = Get-Content file2
foreach ($destination_line in $destination){
$position_destination = ($destination_line.Split())[2]
if ($position_destination -eq $position_source){
$serial_destination = ($destination_line.Split())[1]
}
}
}

And this works fine, now I would like to push $serial_source in place of $serial_destination in file2. How to do it?


error: Connection refused

$
0
0

Can someone please help me, I don't know why I am getting this error\ and how to fix it.

PS C:\WINDOWS\system32> & ("C:\Program Files (x86)\Signalyst\HQPlayer Desktop 3/hqp-control.exe") localhost 'G:\LossLessMusic\HQP-Playlist.m3u8'
hqp-control.exe : error: Connection refused
At line:1 char:1
+ & ("C:\Program Files (x86)\Signalyst\HQPlayer Desktop 3/hqp-control.exe") localh ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (error: Connection refused:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 


TRCNS

installing software remotelly

$
0
0

I have a problem where on some of my 2012R2 servers when I run

Invoke-command -ComputerName $server -ScriptBlock {Start-process -Filepath c:\temp\vcredist_x86.exe -ArgumentList "/install /q /norestart" -Verb RunAs -Wait}

the software installs just fine yet on many my script just stops at this point. Well maybe not exactly stops the execution but doesn't progress so I need to stop it myself. What could be the reason fro that and how to fix or overcome?


yaro

Set-Acl not working even being owner

$
0
0

Hi,

I have a DFS Server in which I have a folder called "F:\home_dir". This folder is shared under "\\myserver\home_dir01$".

The script below has to create all users directory and sets permissions for them, on each directory. The problem is I always have a permission denied.

I already checked for ownership and rights, but the account used to run these operations is the owner of the "home_dir" directory and by the way has full right. (propagate for sure)

Here is the code :

#requires -Version 3 -Modules ActiveDirectory Import-Module -Name ActiveDirectory $DCServer = 'XXX.pierre.be' $DFSServer = 'YYY.pierre.be' $Owner = 'Domain Admins' $SearchBase = 'OU=Users,OU=CSPO Organisation,DC=pierre,DC=be' $User = Get-ADUser -SearchBase $SearchBase -SearchScope 1 -Filter 'samaccountname -eq "test"' #$Users = Get-ADUser -SearchBase $SearchBase -SearchScope 1 -Filter * $SharePath = "\\$DFSServer\homes_dir01$" $PhysicalPath = 'F:\homes_dir' #Predefined Rights $FullRights = [System.Security.AccessControl.FileSystemRights]::FullControl $ModRights = [System.Security.AccessControl.FileSystemRights]::Modify $Inherit = [System.Security.AccessControl.InheritanceFlags]::None $Propagat = [System.Security.AccessControl.PropagationFlags]::InheritOnly $Type = [System.Security.AccessControl.AccessControlType]::Allow #Domain Admin ACE #$AdmAccount = [System.Security.Principal.NTAccount]::new("XXX\$Owner") #$FullACE = [System.Security.AccessControl.FileSystemAccessRule]::new($AdmAccount,$FullRights,$Inherit,$Propagat,$Type) #foreach ($User in $Users) #{ $SamAccountName = $User.SamAccountName if (!(Test-Path $PhysicalPath)) { #Create the folder New-Item -Name $SamAccountName -ItemType Directory -Path $PhysicalPath #Set permissions for dedicated user $UsrAccount = [System.Security.Principal.NTAccount]::new("XXX\$SamAccountName") $ModACE = [System.Security.AccessControl.FileSystemAccessRule]::new($UsrAccount,$ModRights,$Inherit,$Propagat,$Type)

    

$ACL = Get-Acl ("$PhysicalPath\$SamAccountName")
    $ACL.AddAccessRule($ModACE)
    Set-Acl -Path ("$PhysicalPath\$SamAccountName") -AclObject $ACL

    $ACL = Get-Acl ("$PhysicalPath\$SamAccountName")
    $ACL.AddAccessRule($FullACE)
    Set-Acl -Path ("$PhysicalPath\$SamAccountName") -AclObject $ACL

New-DfsnFolder -Path \\pierre.be\homes\$SamAccountName -TargetPath $SharePath\$SamAccountName

} #}

Have you got any idea to help me ?

Regards,

Arnaud H.



InvalidRequestFault Exception while calling method on service using NewWebServiceProxy

$
0
0

I am getting below exception while trying to call the method on available web service.

How to know the actual reason of failure ?

Exception calling "GetServiceProfile" with "1" argument(s): "InvalidRequestFault"
At line:1 char:33
+ $resp = $proxy.GetServiceProfile <<<< ($attributes)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Exception occured while executing below cmd where $attributes is of auto generated type of GetServiceProfile i.e. GetServiceProfileType having msisdn as single param in it.

$proxy.GetServiceProfile($attributes)

PS C:\Windows\system32> $attributes | gm
   TypeName: Microsoft.PowerShell.Commands.NewWebserviceP
_v2_wsdl.GetServiceProfileType

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()
MSISDN      Property   System.String MSISDN {get;set;}

Note: Parameter count is 1 and I have set its type as autogenerated webservice type using namespace and GetType().

AD Custom Schema attribute - String in PSv2, Array in PSv4

$
0
0

Recently created new AD Custom Schema attribute (pbClass), Unicode string, active, indexed and replicated to GC, added to Group class. Used PSv4 to populate this value on a group usingSet-ADGroup GrpName -Replace @{pbClass="Internal"} ... this worked just fine.

Issue:  When I run Get-ADGroup GrpName -Properties pbClass on a PSv4 machine, the value is an array...format-list shows it in {...} and if put result in $array varible, the $array.pbClass has "count" method, value of 1.  When I run same cmd on PSv2, the value is a string, no "count"...GetType() of both results shows Array Collection on PSv4 and String on PSv2.

This is really bugging me...any ideas why this is?


Viewing all 21975 articles
Browse latest View live


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