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

how to show all IP in LAN

$
0
0
How to get a list of all computers IP in a local network using powershell, thank u

How to compare a parameter while calling a function?

$
0
0

Hello,

I have a powershell script with a function doing a switch process. While calling the function in the script I want to compare if the parameter is contained in the switch condition of the function.

function test{ [CmdletBinding()] Param( [Parameter( Mandatory=$False, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$False )] [string]$InputValue ) $Param = switch($InputValue){ A {"string1,string2,string3"} B {"string1,string2,string3"} C {"string1,string2,string3"} } Return $Param

}

If ((test($search)) -match ""){ $scrDynMSGArry = (test($search)).Split(",") $NV = [PSCustomObject]@{ Param = $Param

String1 = $scrDynMSGArry[0] String2 = $scrDynMSGArry[1] String3 = $scrDynMSGArry[2] } }

Error message is: InvokeMethodOnNull for doing the split and reading the array.

I think there is a problem doing the comparison but have no idea to solve this.

Can anybody help?

Regards, Doreen


get total number of onedrive for business documents.

$
0
0
I want to use powershell/graph api for get number of documents(item)/folders. How?

Outlook - Mark All As Read

$
0
0

How does one mark all emails (folders and subfolders) as read in an Outlook mailbox?

I tried this code:

$MyFolders = $outlook.Application.GetNamespace("MAPI").Folders.item("").folders.item("Inbox").Folders

ForEach ($MyFolder in $MyFolders) { ForEach ($Item in $MyFolder.Items.Restrict("[unread] = true")) { $Item.UnRead = $false } }


But it errors with the following:

You cannot call a method on a null-valued expression.
At C:\Users\blashmet\Desktop\Read.ps1:1 char:47
+ $MyFolders = $outlook.Application.GetNamespace <<<< ("MAPI").Folders.item("1_
Employees").folders.item("5_Misc").Folders
    + CategoryInfo          : InvalidOperation: (GetNamespace:String) [], Runt
   imeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\Users\blashmet\Desktop\Read.ps1:3 char:79
+ ForEach ($MyFolder in $MyFolders) { ForEach ($Item in $MyFolder.Items.Restric
t <<<< ("[unread] = true")) { $Item.UnRead = $false } }
    + CategoryInfo          : InvalidOperation: (Restrict:String) [], RuntimeE
   xception
    + FullyQualifiedErrorId : InvokeMethodOnNull

I've tried different combinations of arguments for Folders.item and folders.item. Note that I've renamed my Inbox to "5_Misc".



How to not change the XML format

$
0
0

I have a script that configures an XML document within a zip file. I unzip the file, load the xml doc into the script. Edit values then rezip it. 

This works fine, but when I attempt to submit this to the device I am working on it returns an error. After checking the doc the only thing I can assume is going wrong is that the document is formatted by Powershell in such a way it can no longer be understood by the device. 

To resolve this I have added the .PreserveWhiteSpace and set it to true. This also works, but when I do a comparison, character by character space I notice that there are whitespaces being added within certain xmlnodes. How do I stop this from happening?

Sharepoint 2007 uploads, no sharepoint assembly used

$
0
0

can anyone help?

I am trying to change some code I have for uploading to a sharepoint 2007 server, it currently fails to upload files over 1mb.

both webclient and invoke-webrequest are failing i suspect for the same reason (both lines are commented out in this post)

I cannot use the sharepoint assemblies as the destination sharepoint cannot access the source (that has no sharepoint). 

$path = "\\server1\share"
$Destination = "http://somesharepoitn2007.domain.local/SiteDirectory/Site"
 
$settingsfile = ".\cred.txt"
$securePasssword = Get-Content $settingsfile| ConvertTo-SecureString;
$credentials = New-Object System.Management.Automation.PSCredential ("domain\user", $securePasssword);
$webclient = New-Object System.Net.WebClient;
$webclient.Credentials = $credentials;
 
 
$myfile = $Destination + "/" + $_.Name
 
#Get-ChildItem $path | Where-Object {$_.Length -gt 0} | ForEach-Object {$_.Name;$webclient.UploadFile($destination + "/" + $_.Name, "PUT", $_.FullName)};
#Get-ChildItem $path | Where-Object {$_.Length -gt 0} | ForEach-Object {$myfile = $Destination + "/" + $_.Name; Write-Host $myfile; Invoke-WebRequest -TimeoutSec 10 -DisableKeepAlive -Uri $myfile -Method Post -InFile $_.FullName -ContentType"multipart/formdata" -UseDefaultCredentials};



kittuk

how can get Timezone information of DCs in powershell

$
0
0
I have 500 DCs list in CSV file with header of name

I need to pull out the all DCs timezone information.

Is there any way to get the time zone details for each DC with powershell


i have searched google but could not find nice solutions.

I tried with Get-WMIObject but using that getting access denied due to I have list of DCs of my 
4 domains in single forest.

Please suggest any script or powershell function to get the data.

Powershell script to rename all files and folders to lowercase in a directory?

$
0
0

Hello,

I have a folder with multiple subdirectories and files, that must all follow a lowercase naming format before they are copied to an IBM AIX server.

Can anyone out there help with a Powershell script that will rename all files and folders to lowercase?

Thanks Stuart.


Message instead of exception

$
0
0

Hi,

I don't want to display the red exception information:

Invoke-Sqlcmd : Database 't_db_mgm' does not exist. Make sure that the name is entered correctly.

At D:\Scripts\MSSql\Powershell\installSPTest Step 2.ps1:110 char:20

+     ForEach-Object{Invoke-Sqlcmd  -ServerInstance $_ -Database master -Query  $c ...

+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException

    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

Invoke-Sqlcmd : Database 't_db_mgm' does not exist. Make sure that the name is entered correctly.

At D:\Scripts\MSSql\Powershell\installSPTest Step 2.ps1:110 char:20

+     ForEach-Object{Invoke-Sqlcmd  -ServerInstance $_ -Database master -Query  $c ...

+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException

    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

But I want to display my own tekst, "Please run database script first".

What is the best way to do this?

Code example:

Try { Get-Content $input | ForEach-Object{Invoke-Sqlcmd -ServerInstance $_ -Database master -Query $createSP } } Catch {

"caught a system exception" } Finally {"end of script" }


Kind regards,

André

How to fill color in a cell having particular string when using convertto-html

$
0
0

Hello Scripters,

I have downloaded AD health check script but I am wondering if the cell color be changed for a particular string. Like all the cells having text "Failed"..should be in red color.

Here is the script-

Function Getservicestatus($service, $server) { $st = Get-service -computername $server | where-object { $_.name -eq $service } if($st) {$servicestatus= $st.status} else {$servicestatus = "Not found"} Return $servicestatus } $Forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest() [string[]]$computername = $Forest.domains | ForEach-Object {$_.DomainControllers} | ForEach-Object {$_.Name} #Section -1

$report= @() foreach ($server in $computername){ $temp = "" | select server, pingstatus if ( Test-Connection -ComputerName $server -Count 1 -ErrorAction SilentlyContinue ) { $temp.pingstatus = "Pinging" } else { $temp.pingstatus = "Not pinging" } $temp.server = $server $report+=$temp } $b = $report | select server, pingstatus | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>Server Availability</h2>" | Out-String

#Section - 2 $report = @() foreach ($server in $computername){ $temp = "" | select server, KDC, NtFrs, DFSR, netlogon, w32Time $temp.server = $server $temp.KDC = Getservicestatus -service "KDC" -server $server $temp.NtFrs = Getservicestatus -service "NtFrs" -server $server $temp.DFSR = Getservicestatus -service "DFSR" -server $server $temp.netlogon = Getservicestatus -service "netlogon" -server $server $temp.w32Time = Getservicestatus -service "w32Time" -server $server $report+=$temp } $b+= $REPORT | select server, KDC, NtFrs, DFSR, netlogon, w32Time | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>Service Status</h2>" | Out-String #Section - 3

add-type -AssemblyName microsoft.visualbasic $strings = "microsoft.visualbasic.strings" -as [type] $report = @() foreach ($server in $computername){ $temp = "" | select server, Netlogon, Advertising, Connectivity, Replication $temp.server = $server $svt = dcdiag /test:netlogons /s:$server $svt1 = dcdiag /test:Advertising /s:$server $svt2 = dcdiag /test:connectivity /s:$server $svt3 = dcdiag /test:Replications /s:$server if($strings::instr($svt, "passed test NetLogons")){$temp.Netlogon = "Passed"} else {$temp.Netlogon = "Failed"} if($strings::instr($svt1, "passed test Advertising")){$temp.Advertising = "Passed"} else {$temp.Advertising = "Failed"} if($strings::instr($svt2, "passed test Connectivity")){$temp.Connectivity = "Passed"} else {$temp.Connectivity = "Failed"} if($strings::instr($svt3, "passed test Replications")){$temp.Replication = "Passed"} else {$temp.Replication = "Failed"} $report+=$temp } $b+= $REPORT | select server, Netlogon, Advertising, Connectivity, Replication | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>DCDIAG Test</h2>" | Out-String #Section - 4 $workfile = repadmin.exe /showrepl * /csv $results = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -ge 1} #$results = $results | where {$_.'Number of Failures' -gt 1 } if ($results -ne $null ) { $results = $results | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" $b+= $results | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>Replication Status</h2>" | Out-String } else { $results = "There were no Replication Errors" $b+= $results | ConvertTo-HTML -Fragment -PreContent "<h2>Replication Status</h2>" | Out-String } $head = @' <style> body { background-color:#dddddd; font-family:Tahoma; font-size:12pt; } td, th { border:1px Solid Black; border-collapse:collapse; } th { color:white; background-color:DarkGoldenRod; } table, tr, td, th { padding: 2px; margin: 0px } table { margin-left:50px; }</style> '@ $s = ConvertTo-HTML -head $head -PostContent $b -Body "<h1>Active Directory Checklist</h1>" | Out-string $emailFrom = "" $emailTo = "" $smtpserver= "" $smtp=new-object Net.Mail.SmtpClient($smtpServer) $msg = new-object Net.Mail.MailMessage $msg.From = $emailFrom $msg.To.Add($emailTo) $msg.IsBodyHTML = $true $msg.subject="Active Directory Health Check Report From Dlhdc02" $msg.Body = $s $smtp.Send($msg)

Like in the Ping Status (section - 1), I'd like all the cell having text "Not Pinging" should be in RED color.

Also I am facing an issue in the (Section - 4). When the value of $Results is not null I am getting the desired output but when the value is null the text ""There were no Replication Errors""  is not getting displayed in the HTML body. Instead it comes as "*32" (32 is the number of letters in the text).

Please help me in fixing this ....

BR

Himanshu


MCTS|MCSE|MCSA:Messaging|CCNA


Powershell loop with a sleep statement

$
0
0

Hi,

I am very much a newbie to powershell and I am trying to understand some of it before taking my 70-417 exam.

I was working through the Hyper-V resource monitoring and looked at the command Measure-VM -VMName servername and I thought that the command would be more use if you could run it in a loop every few seconds so you can see more about what is happening on your server.

To do this I tried the following script:

$i = 1

do{
Measure-VM -VMName Servername
$i++

}

while ($i -le 5)

This displayed the results five times in a row but did not space them out over time. I then tried adding Start-Sleep in the loop but that just waited the allotted time times 5 and then displayed the same information.

How do I make this run every few 2 seconds.

I think in the end what I am looking for is to have a script that when run asks me which server to monitor, how many loops and how many seconds to wait in between the loop.

Any help gratefully received.

Thanks,

alamb200

Why does my script ignore values in variable only some of the time?

$
0
0

Hello,

I'm a beginner at Powershell and am writing a script to gather the deployment details on all Azure Cloud Services attached to a Azure Subscription, including the info for any service that does not have a deployment.  

I understand that the way I'm going about this may be wrong and I am NOT looking for any help creating a final script.  Some of my script is written specifically so that I can better understand what it's doing (for learning purposes).

What I am looking for is help understand why my current script behaves the way it does.

Here's my current script:

###
#Create a report that shows the created date and latest deployment date for all
#hosted services (cloud services)deployments in MyAzureSubscription
###
Select-AzureSubscription MyAzureSubscription
$ServiceNames = Get-azureservice

foreach ($service in $ServiceNames){

        $ServiceName = $service | select -ExpandProperty ServiceName
        $ServiceDateModified = $service | select -ExpandProperty DateModified
        $service |
        get-azuredeployment -ErrorAction SilentlyContinue -ErrorVariable NoDeployment |
        Select @{Name="ServiceName";Expression={$ServiceName}}, DeploymentName, Status, CreatedTime, LastModifiedTime, @{Name="ServiceDateModified";Expression={$ServiecDateModified}}, @{Name="NoDeployment";Expression={$NoDeployment}} |
        Sort-Object -Propert DeploymentName |
        export-csv "outputfile.csv" -notypeinformation -append

        #Test statements below
        #Write-Host "NoDeployment Below:"
        #$Service | select ServiceName | Write-Host
        #Write-Error $NoDeployment
        Write-Host $ServiceName
        }

The output file only contains a list of servicenames and deployment details for services that do have a deployment.  None of the services that have no deployments are added/exported to the csv file.  However, the "write-host $ServiceName" writes ALL the service names in the powershell window, regardless of whether there's a deployment or not.

What I don't understand is why the Select @{Name="ServiceName";Expression={$ServiceName}} only outputs the service names of services that have deployments instead of ALL service names regardless of whether they have a deployment or not.

I've already proven that the variable $ServiceName does, at some point, save the ServiceName into the $ServiceName variable by writing it to host on each iteration of the foreach loop.  So why is it ignoring some ServiceNames when outputting/exporting to the csv file?

Thanks!

list services as colums

$
0
0

hi

i'm using this code from this forum https://social.technet.microsoft.com/Forums/windowsserver/en-US/75b3dcde-af1e-4d87-9eff-ce923b090ef8/get-services-from-remote-computers

$array = @()            
foreach($i in (gc c:\computers.txt)) {            
 $svc = Get-Service winrm -ComputerName $i -ea "0"            
 $obj = New-Object psobject -Property @{            
  Name = $svc.name            
  Status = $svc.status            
  Computer = $i            
  }            
 $array += $obj            
}                      
$array | Select Computer,Name,Status | FT -AutoSize

this  works fine for multiple computers and one servic but how can i verify 3 services at time...i'm loking to achieve this:

serverservice1service2service3

server1Runningrunningstoped

server2Runningstopedrunning

server3Runningrunningrunning

thanx 

Using "Schedule.Service API" with RegisterTaskDefinition

$
0
0

I'm needing to automate numerous tasks, one of which is a scheduled task that runs indefinitely.  I want to be able to stop and start the scheduled task via powershell.  To do so it is my understanding the job must be registered via powershell. There are parameters that I need to set where I need to use the "Schedule.Service API".  I'm close to having a working solution but need some help in setting the "RegisterTaskDefinition" which is the last line in the script below. 

Can anyone give me some counsel on setting this correctly?


# http://www.verboon.info/2013/12/powershell-creating-scheduled-tasks-with-powershell-version-3/
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa382577(v=vs.85).aspx

$UserAcct = "Domain\acctname"
$UserPass = ConvertTo-SecureString "somepass" -AsPlainText -Force
$UserCred = New-Object System.Management.Automation.PSCredential($UserAcct, $UserPass)

# The name of the scheduled task
$TaskName = "MyScheduledTask"
# The description of the task
$TaskDescr = "Run a powershell script through a scheduled task"
# The Task Action command
$TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
# The script to be executed
$TaskScript = "D:\MySQLAdmin\Scripts\MySQLFailoverService.cmd"
# The Task Action command argument
$TaskArg = "-NonInteractive -Executionpolicy unrestricted -file $TaskScript"

# The time when the task starts, for demonstration purposes we run it 1 minute after we created the task
$TaskStartTime = [datetime]::Now.AddMinutes(5) 

# attach the Task Scheduler com object
$ScheduleObject = new-object -ComObject("Schedule.Service")
# connect to the local machine. 
$ScheduleObject.Connect()
$rootFolder = $ScheduleObject.GetFolder("\")

$TaskDefinition = $ScheduleObject.NewTask(0) 
$TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
$TaskDefinition.RegistrationInfo.Author = "My Name"
#$TaskDefinition.Principle.RunLevel = $true
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$TaskDefinition.Settings.DisallowStartIfOnBatteries = $false
$TaskDefinition.Settings.ExecutionTimeLimit = "PT0S"  # See Note Below

$triggers = $TaskDefinition.Triggers
$trigger = $triggers.Create(8) # Creates a "At System Startup" trigger
$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.Enabled = $true

$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand"
$action.Arguments = "$TaskArg"

$rootFolder.RegisterTaskDefinition($TaskName,$TaskDefinition,6,$UserAcct,$UserPass,1)

     

Removing an Excel Addin

$
0
0

I can easily add an addin to excel using the syntax around this command

$excel = New-object -ComObject excel.application 

$excel.workbooks.add()

But I am not aware of a command to remove an addin when using -ComObject excel.application

Example "$excel.workbooks.delete()" is not a real command. You can methodically add an xla file but not remove it? Any ideas?


ExecutionContext.InvokeCommand.ExpandString throws exception in PowerShell 4.0

$
0
0

I have a script as below

[string]$newValue = Get-ConfigurationByType $setting.Value

After this line, the value of $newValue is

"http://ST-$($partner.Alias).vardiaforsakring.se/CardPaymentAgreementCallback.aspx"

In the loop, I call ExpandString

foreach ($partner in $partners)
{
    $partnerSpecificValue =$ExecutionContext.InvokeCommand.ExpandString($newValue)
}

It throws exception

Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an object." At C:\Programs\Drops\Hydra_SE_v1.28\HydraDeploymentFunctions.ps1:342 char:5+ $partnerSpecificValue = $ExecutionContext.InvokeCommand.ExpandString($newVal ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : NullReferenceException

But when I try to input hard-code string, it returns expected result without exception

$partnerSpecificValue =$ExecutionContext.InvokeCommand.ExpandString("http://ST-$($partner.Alias).vardiaforsakring.se/CardPaymentAgreementCallback.aspx")

The value of $partnerSpecificValue is

http://ST-secure.vardiaforsakring.se/CardPaymentAgreementCallback.aspx


How to use TRAP to remove the error messages in a script

$
0
0

Hello,

I found in a other thread a script for looking up IP Addresses in a subnet and rebuild it a bit that it also resolves the hostname, but if there is no hostname it gives an error. Is it possible to remove those messages with TRAP? I've tried to implement it, but without any success.

1..254 |
    %{
      $IP= "172.18.10.$_"
	  $name = ([System.Net.Dns]::GetHostbyAddress("$IP")).HostName
	  if(Test-Connection $IP -count 1 -q){"Found $IP - $name"
			}
	}


Overwrite Zip contents

$
0
0

Hi guys,

Over the past month I have been trying to write a script that extracts it's contents, makes changes and then rezips it. Unfortunately I need to change the requirements of the script so that instead of creating a new zip file, I need to overwrite the current one. 

Here's my code right now:

[io.compression.zipfile]::CreateFromDirectory("C:\temp\contents\","C:\test\test.zip")


So the .zip file already exists at this location. What I want to see is that the contents of the test.zip get overwritten. This instead does nothing. It's really important that the zip is not deleted, just that it's contents are overwritten. 

Is there anyway to do this? 

EDIT: I do get an error.

"Exception calling "CreateFromDirectory" with 2 arguments: "C:\test\test.zip" already exists."

Task scheduler - restart program or process

$
0
0

Hello,

I have a issue with powershell. Every time, when I try to use scheduled task, where I restart a process or a program, that step doesn´t work. It works perfectly when it is not run as a scheduled task. I have script rights elevated, so it should not be blocked by that. Is there anything else, that could block this kind of scripts?

Thanks a lot, Martin.

Home Folder Permissions

$
0
0

Hi

I have the below script which works great, accept setting permissions on the home folder. Can anyone help with the exception at the end?

import-Csv .\users.csv | foreach-object {$userprinicpalname = $_.SamAccountName + "@castlemanor.local"

Import-Module ActiveDirectory

# Creates a new staff user in Active Directory

New-ADUser -SamAccountName $_.SamAccountName -UserPrincipalName $userprinicpalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Department $_.Department -Company $_.Company -Homedrive $_.HomeDrive -HomeDirectory $_.HomeDirectory -Path"OU=Staff,OU=CL10,DC=castlemanor,DC=local" -AccountPassword (ConvertTo-SecureString "Microsoft~1;" -AsPlainText -force) -Enabled $True -ChangePasswordAtLogon $True -PassThru


# Adds the memeber to the Staff security group

Add-ADGroupMember "Staff" $_."SamAccountname";

# Sets the users home directory

Set-ADUser $_.SamAccountName -HomeDirectory $_.HomeDirectory -HomeDrive u;

# Creates the users home folder on the file server and build access rule to set permissions

New-Item -path $_.HomeDirectory -type directory -force
$Domain='castlemanor'
$acl = Get-Acl $_.HomeDirectory
$permission = "$_.SamAccountName","FullControl","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl $_.HomeDirectory
}

This is the exception I get:

Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity
references could not be translated."
At C:\Scriptfinalv1.2 - Restored.ps1:25 char:1
+ $acl.SetAccessRule($accessRule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : IdentityNotMappedException

Thanks for any advice in advance

Shane 

Viewing all 21975 articles
Browse latest View live


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