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

PS1 to Monitor Availability Group ROLE

$
0
0

I'm new to Powershell and have been tasked to create a script to monitor the state of our AG groups, and to Fail them back when REPLICA ROLE has change (indicating a failover occurence.). Running in the SQL shell SQLPS-the path to the REPLICA ROLE is as follows: PS SQLSERVER:\SQL\MyServerName\DEFAULT\AvailabilityGroups\MyAG\AvailabilityReplicas> dir 

NameRole ConnectionStateRollupSynchronization

I need the script to ID the Role change then IF/ELSE 

Switch-SqlAvailabilityGroup -Path SQLSERVER:\Sql\MySQLServer\DEFAULT\AvailabilityGroups\MyAG



Export-CSV from an array

$
0
0

Trying to understand how to export objects properly. In script 1 the items all appear in one cell, but in script 2 the items are properly formatted in the CSV sheet with proper columns and rows with data per cell.

How can I rewrite script 1 to avoid all items in a cell?


Script 1 example

$get=get-vm "*"

$get|export-csv c:\temp\info.csv -notypeinformation

____________________________________

Script 2 example

$list = gc c:\temp\list.txt|where {$_ -ne $null}

$top=ForEach($l in $list){

 get-vm -name $l

}

$top|export-csv c:\temp\info.csv -notypeinformation

_______________________

Script 1 output 

Name {server1,server2,server3}

Powerstate {poweredOn, poweredOn, PoweredOn}

__________________________

Script 2 output

Name               PowerState


server 1            poweredOn

server 2            poweredOn

server 3            poweredOn








PowerShell - Obtain parameter from SSRS report

$
0
0

Hello

I'm using PowerShell to render SSRS reports. The report I'm trying to render has a parameter that is dependent on the value(s) selected from the first parameter. I'm trying to obtain the valid values for this second parameter. Is there a way to render the report using the first parameter value to return the ValidValues available for the second parameter please? This is the code I have so far:

#-------------------------------------------------------------- 
# add assembly 
#-------------------------------------------------------------- 
Add-Type -AssemblyName "Microsoft.ReportViewer.WinForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"

#-------------------------------------------------------------- 
# create timestamped folder 
# where we will save our report 
#-------------------------------------------------------------- 
$dt = Get-Date -Format "yyyy-MMM-dd hhmmtt" 
$baseFolder = "\\Folder1\"
$tempfolder = "\\Folder1\Excel files\"

# if the path exists, will error silently and continue 
New-Item -ItemType Directory -Path $baseFolder -ErrorAction SilentlyContinue | Out-Null

$ReportServerUri = "http://ServerName/ReportServer//ReportService2005.asmx?wsdl"
$global:proxy = New-WebServiceProxy -Uri $ReportServerUri  -UseDefaultCredential;
$items = $global:proxy.ListChildren("/", $true) |
         Where-Object {$_.Path -like "/ReportFolder/*"};

ForEach ($i in $items){
#-------------------------------------------------------------- 
# report Server Properties 
#-------------------------------------------------------------- 
$rv = New-Object Microsoft.Reporting.WinForms.ReportViewer
$rv.ServerReport.ReportServerUrl = "http://ServerName/ReportServer" 
$rv.ServerReport.ReportPath = $i.Path
$ReportName = $i.Name
$rv.ProcessingMode = "Remote"

$rv.ServerReport.GetParameters()| Where-Object {$_.Name -eq "P_Reg"}|
ForEach-Object {
    $param = $_
    $validValues1 = ""
    $validValues3 = ""
    if ($param.ValidValues -ne $null)
    {
        $validValues1 = [string]::Join(",", ($param.ValidValues[-1..-1] |
                       ForEach-Object {$_.Value}))
$validValues3 = $param.ValidValues[-1..-1] |
                       ForEach-Object {$_.Value}
    }
}

$rv.ServerReport.GetParameters()| Where-Object {$_.Name -eq "P_Qual"}
}

Powershell to Remove Ghost SID from OUs

$
0
0

Hi. I had hoped to figure this out on my own, but I threw up my hands and decided to ask.

We migrated our domain from a parent company and hundreds of OUs now have orphaned SIDs.  I would like to use Powershell to take a CSV file listing the DistinguishedName of the OU and remove the dead SID.

I thought it would be based on this command, but it seems more involved.

Get-Acl-Path"AD:\OU=CompanyComputers,DC=wingtiptoys,DC=local"|Where-object($_.IdentityReference-like'S-1-5-21-9999705215-1832128825-2807327032-512')|(RemoveProblemSID)

Has anyone run into this situation before?  I see several for sale utilities which do the same, but I was hoping PS could do the work.

Thanks

Executing tasks on Incident

$
0
0

Hello Everyone,

We have a task (Task A) in SCSM on our incident forms, that we click and execute when we want to. This is a vendor supplied task and we do not have the code behind it.

My question is how can we run this task using PowerShell so that we do not have to click on it? I can get this task by using the command Get-SCSMTask but I can find any command to run it.

I am creating a new task (Task B) that does something + executes Task A. Any help will be greatly appreciated.

Thanks in advance 

Add-MailboxPermission Problem

$
0
0

I'm trying to add MailBox permissions using 2 inputted variables but I get an error.

Set-ExecutionPolicy Unrestricted
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
$username = Read-Host -Prompt 'User Account'
$displayname=(Get-ADuser -Id $username -Properties DisplayName).DisplayName
write-host "Username is $username and dispalyname of user is $displayname."
$MailboxDisplayName = Read-Host -Prompt 'Enter display name of user you are giving access to their mailbox'
$UsernameofMailboxAccess = (Get-ADUser -ldapfilter "(displayname=$MailboxDisplayName)" -Property samaccountname).samaacountname

Write-Host "You are giving  $MailboxDisplayName access to $displayname's mailbox"

Add-MailboxPermission -Identity "$displayname" -User $UsernameofMailboxAccess -AccessRights Fullaccess -InheritanceType all

Does anyone know why?

I'm following: 

https://technet.microsoft.com/en-us/library/bb124097(v=exchg.160).aspx

It works fine with no variables 


Object with several properties using at one time

$
0
0

Hello, guys

I’m getting properties by this command.

Get-CMDistributionPoint-SiteSystemServerName"*"-ForceWildcardHandling

FileType     : 2

ItemName     : ["Display=\\WX1687.mydomain.net\"]MSWNET:["SMS_SITE=DKA"]\\WX1687. mydomain.net \,SMS Distribution Point

ItemType     : System Resource Usage

NALPath      : ["Display=\\WX1687. mydomain.net \"]MSWNET:["SMS_SITE=DKA"]\\WX1687. mydomain.net \

NALType      : Windows NT Server

NetworkOSPath : \\WX1687. mydomain.net

PropLists    : {BindExcept, Objects Polled By Site Status, Protected Boundary}

Props        : {ADSiteName, AllowInternetClients, AvailableContentLibDrivesList, AvailablePkgShareDrivesList...}

RoleCount    : 7

RoleName     : SMS Distribution Point

SiteCode     : DKA

SslState     : 0

Type         : 1

I’m using propertie NetworkOSpath, to get server names and put it to variable $DP

(Get-CMDistributionPoint-SiteSystemServerName"*"ForceWildcardHandling).NetworkOSpath

But then Im trying to set distribution point from variable on which used networkOSpath it doesn’t work

Because for Set-CMDistributionPoint-InputObject $DP need SiteCode propertie example DKA

$ValidationSchedule1=New-CMSchedule-Start $(Get-Date-Year2016 -Month08-Day29-Hour 0-Minute0-Second0) -DayOfWeekMonday

Set-CMDistributionPoint-InputObject$DP-EnableValidateContent $true-ValidateContentSchedule $ValidationSchedule1

How can I use  Set-CMDistributionPoint which can read two properties and understand

Command with required sitecode?

Detect if BitLocker Protection Status is 0, enable

$
0
0

Hi,

I tested each command separately and it works.

1. Use Enter-PSSession -ComputerName DCBLT222

2. manage-bde.exe -status c:

Protection Status: Protection Off

3. manage-bde.exe –protectors –enable c:

Protection Status: Protection ON

I would like to run this against 100 laptops. Script below shows error:

a. .\manage-bde.exe-protectors-enable C:

ERROR: An error occurred (code 0x8004100e):
Invalid namespace

b. Resume-BitLocker -MountPoint "C:"

Get-CimInstance : Invalid namespace

At C:\windows\system32\windowspowershell\v1.0\Modules\BitLocker\BitLocker.psm1:

146 char:13

+             Get-CimInstance `

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

    + CategoryInfo          : MetadataError: (root\cimv2\Secu...cryptableVolum

   e:String) [Get-CimInstance], CimException

    + FullyQualifiedErrorId : HRESULT 0x8004100e,Microsoft.Management.Infrastr

   ucture.CimCmdlets.GetCimInstanceCommand

Get-Win32EncryptableVolumeInternal : C: does not have an associated BitLocker

volume.

At C:\windows\system32\windowspowershell\v1.0\Modules\BitLocker\BitLocker.psm1:

358 char:35

+ ... bleVolume = Get-Win32EncryptableVolumeInternal -MountPoint $MountPoin ...

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

    + CategoryInfo          : NotSpecified: (:) [Write-Error], COMException

    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Get-

   Win32EncryptableVolumeInternal

__________________________________________________________________

SCRIPT:

   $Computer="DCBLT222"


If(Test-Connection-ComputerName$computer-Quiet) {

       

If($encryption_check_all=Get-WMIObject-ComputerName$computer-Namespace"root/CIMV2/Security/MicrosoftVolumeEncryption"`

       

-query"SELECT * FROM Win32_EncryptableVolume WHERE DriveLetter='C:'"|Select-Object*){

     

$protection_check=$encryption_check_all.ProtectionStatus

     

$protection_check

        }

If($protection_check-eq"0"){

           

.\manage-bde.exe-protectors-enableC:


           

#Resume-BitLocker -MountPoint "C:"


            }

           }

else{}

         






Adding Azure powershell module to win10 fails.

$
0
0

I'm on win10. Trying to add the Azure module (clasic not RM) so I can work with my Azure vms.

I run install-module azure, it goes through and installs then I get an error that the command Get-AzureStorageContainerAcl already exist and if I want to install the module I need to use the -allowclobber parameter. Issue is -allow parameter doesn't seem to be valid for install-module.

Get-Module -ListAvailable doesn't list the azure module, just azure.storage and azureRM.profile


Enterprise technology blog

How Do I Modify Folder Time Stamps? Altering Folder Creation Time, Last Access Time and Last Write Time

$
0
0

Hello,

I need to change time stamp on my folders. I created a small script, which, however, seems to not be working. What am I doing wrong? Could somebody please help here?

The script:

Function Set-FileTimeStamps

{

 Param (

    [Parameter(mandatory=$true)]

    [string[]]$path,

    [datetime]$date
        )

    Get-Item -Path $path |

    ForEach-Object {

     $_.CreationTime = $date

     $_.LastAccessTime = $date

     $_.LastWriteTime = $date
     }

}

This one returns:

Exception setting "CreationTime": "The process cannot access the file 'F:\Downloads\Test1' because it is being used by another process."

A one-liner would be:

$(Get-Item F:\Downloads\Test1).LastWriteTime = $(Set-Date "12/12/2012")

This one returns:

Set-Date : A required privilege is not held by the client

At line:1 char:50

Both don't work for me.

Could somebody please help me to get what's wrong here and what would be the proper solution?

Thank you.


Well this is the world we live in And these are the hands we're given...

How to move and replace files in fileshares using Move-Item

$
0
0

Hello,

We need to set the CreationTime of Files to be now, then move from one File Share to another File Share with the destination file being replaced if one with the same name if present.

The move-item moves the files from the source file share, but does not replace liked named files in the destination file shares using PS V2 on Server 2008 R2 or PS V4 on Server 2012 R2.

The code below works fine except the destination file is not replaced.  Any suggestions on how to move and replace using File Shares?

$Updates         = "\\FS1\Updates"
$Load            = "\\FS1\Load"

$DateTime = Get-Date -Format G

$AllFiles = Get-Childitem $($Updates)

Foreach ($File in $AllFiles)
  {
  $($File).CreationTime = "$DateTime"
   Move-Item -Path ($($Updates) + "\" + $($File)) -Dest $($Load) -Force
  }


Thanks for your help! SdeDot

powershell script - list all remote users connected via RDP (with details like: remote workstation name, ip address, login time)

$
0
0

Hi,

I want to have a script that will gather information about logged users via RDP to the server with specific details:
username, ip address, workstation name and time when logins.

I have found script that gives me username and time but can't find rest.

I will use this script to run after trigger "at log on/of any user" in task scheduler.

Please help.


$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
if ($explorerprocesses.Count -eq 0)
{"No explorer process found / Nobody interactively logged on"
} else {
    foreach ($i in $explorerprocesses)
    {
        $Username = $i.GetOwner().User
        $Domain = $i.GetOwner().Domain
        $Domain + "\" + $Username + " logged on since: " + ($i.ConvertToDateTime($i.CreationDate))
    }
} 

Powershell: DFSR format-table path not showing UNC information

$
0
0

Hello,


Working with 2012 R2. When I execute (for example) the following powershell code for a DFS receiving member, I don't see any path information. Any other format is showing information. SourceComputerName, Inbound, UpdateState, etc. Only 'path' only returns empty space. I tested this several times, backlog is showing downloads.


Get-DfsrState -computername MyLittleServer | Format-Table path

I'm only getting the following output:

Path
----




Anyone know what this might be causing?

Thanks in advance,

Ingmar





how to get record count and record that to log file

$
0
0

 How can I get a record count of the dumped records to the csv file, and also record that in separate log files based upon the table dumped? I want to verify what load to csv equals what's in the database

$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Server=$dbserver; Database=$dbname;Integrated Security=SSPI"
$con.Open()
$sql = $con.CreateCommand()
$Sql.CommandTimeout = 0
$sql.CommandText = "SELECT * FROM [$dbname].[INFORMATION_SCHEMA].[TABLES] where table_name like 'Import_iacts%' and table_type = 'Base Table'"
$result = $sql.ExecuteReader()
$tables = New-Object System.Data.DataTable
$tables.Load($result)
[int32]$i = 0;
foreach($table in $tables)
{
    Write-Progress -Activity "Fetching tables" -Status $table.TABLE_NAME -PercentComplete ($i/$($tables.Rows.Count)*100)
    $i++
    $sql.CommandText = "SELECT * FROM [$dbname].[$($table.TABLE_SCHEMA)].[$($table.TABLE_NAME)] With (Nolock) where datepart(yyyy,datetime) = $yy and datepart(mm,datetime) = $mm and datepart(dd,datetime) = $dd"
	Write-Host $sql.CommandText
    $result = $sql.ExecuteReader()
    $data = New-Object System.Data.DataTable
    $data.Load($result)
    $data |Export-Csv "$exportpath\$dbserver.$dbname.$($table.TABLE_SCHEMA).$($table.TABLE_NAME)_$fileext.csv" -NoType
}
$con.Close()

 Thanks.

run as administrator

$
0
0

Hi 

I am running onw poershell script on server but I cannot see run as administrator option after right click.

How can I get that options on windows 2008R2.

IS there any tooll or command to conver powershell script o exe program.

?


POWERSHELL Command to turn on a set of hosts remotely.

$
0
0
I am in need of a command that will allow me to turn on a set of hosts on a specific server remotely. Thank you. 

Compare-Object : Cannot bind argument to parameter 'ReferenceObject' because it is null.

$
0
0

I am trying to use the Compare-Object to see if a file is in a specific folder. I tried to put File3.txt in a different location to see if it would tell me that I am missing File3.txt and only found File1-2.txt

Inside File1.txt is "File1" for File2.txt "File2" and File3.txt "File3"

$a = @("File1.txt","File2.txt","File3.txt"
)
$b = Get-ChildItem -Path "C:\test\folder"
Compare-Object -ReferenceObject $a -DifferenceObject $b

How can I fix this error, it is really frustrating.


Compare Files in a folder

$
0
0

Hi All,

I need a script which will compare the latest 2 files ( HTML ) in a specific folder and send changes in a email.

Please Note : New File Gets generated every 10 min. Filename format like ConnectionCheck_31082016-080215.html

Format Should be in : DDMMYYYY-HHMMS

Please help

Using Office attribute in Exchange

$
0
0

I am trying update the Office attribute via Powershell using the following command:

Set-Mailbox $i.UPN -CustomAttribute5 $i.Office -CustomAttribute2 $i.CustomAttribute2 -Office $i.Office

However, an error is being displayed stating:

Cannot convert 'System.String' to the type 'System.Boolean' required by parameter 'OfficeGraph'. 
At C:\Users\XXXX\AppData\Local\Temp\tmp_4yt2zdvn.axc\tmp_4yt2zdvn.axc.psm1:51130 char:9
+ $steppablePipeline.End()
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Mailbox], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Exchange.Management.RecipientTasks.SetMailbox


I tried to figure out what the problem is and the above function works when I remove "-Office $i.Office". I also know that the variable "$i.Office" is correct since CustomAttribute5 is updated with the same value, hence the problem lies in the Office attribute. I know that this script worked before so I can't understand why it is not working now.

get-acl only show groups not users

$
0
0

Hi

I was looking to get a mapping of shared folders to their security groups

Catch is i don't want all the end users listed just the groups   e.g.   "domain admins"  "accounts department"     but not   user accounts like "john doe" "Suzy ann".

I see that I can use Get acl against a shared folder which is great

e.g.   get-acl  \\server1\share3

Im looking to get a mapping for the \\server1\shares3   and all its sub folders in the end

I cant see how to specify that I only want groups returned not users  e.g.   get-acl \\server1\share2 | select group

Thanks for reading

Confuseis


confuseis

Viewing all 21975 articles
Browse latest View live


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