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

Show all AD users who have disinherited permissions

$
0
0

Hi, I need to be able to query for users who have their Domain Security inheritance disabled.

Has anyone got any idea please?

Thanks very much


Phil


Powershell script to change SMTP configuration

$
0
0

Hi!

I have a powershell script which I'm using to set up a number of identical Server 2008 R2 boxes.  We have the microsoft SMTP service installed (as "virtual server #1") but I can't find Powershell code to change the properties such that the SMTP service (which can only be manipulated via IIS 6 manager) allows the local system to relay through it.  We have both an application (and the PS script) that need to be able to send emails, but it only works if we set the local relay to be allowed.

Security is not an issue on the open relay.

I've seen references to VB, and even one to a purchasable cmdlet - neither of which are really options.

Ideas?

Thanks in advance!

Lee

Computers, ExpandProperty memberof and export-csv

$
0
0

Hello there,

I am trying to get a list of all computers that are members of a particular group. I have the following which does the job but I need a little extra.

Get-QADComputer-SizeLimit0-OSName*7*-NamePC000*-IncludedPropertiesmemberof|


where

{$_.memberof-like"*ABC*"}|


select

name,{$_.memberof},description,whenchanged,accountisdisabled,parentcontainer|


Export-Csv

-PathC:\Temp\list.csv

This gives me what I want but the member of is a long string of CN=..., CN=...

Since I am matching the group name, I cannot be more specific, I might get hits which are from a different group. So what I want to do get is the following.

Name, memberof

PC001,CN=1

PC001,CN=2

PC001,CN=3

PC002,CN=1

PC002,CN=2

Thank you in advance.

SMTP Configuration

$
0
0

I have a powershell script to set the SMTP configuration on new servers (Server 2012) and send a test email

But it doesn't seem to work until you open the IIS6 manager and the properties of the SMTP virtual server then close it. You don't have to change anything just open and click ok. until you do that the email is stuck in the C:\inetpub\mailroot\Queue

# Set SMTP
Write-Host -Foregroundcolor Red " Configuring SMTP " 
Set-Service "SMTPSVC" -StartupType Automatic -ErrorAction SilentlyContinue
Start-Service "SMTPSVC" -ErrorAction SilentlyContinue
$SmtpConfig = Get-WMIObject IISSMTPServerSetting -Namespace root/MicrosoftIISv2
$Relay = @(24,0,0,128,32,0,0,128,80,0,0,128,88,0,0,128,1,0,0,0,96,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,104,0,0,128,2,0,0,0,2,0,0,0,4,0,0,0,0,0,0,0,96,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,127,0,0,1,255,255,0,0,172,20,0,2)
$SmtpConfig.RelayIPList = $Relay
$SmtpConfig.SmartHost="smtp.mydomain.com"
$SmtpConfig.DontLog=$False
$SmtpConfig.LogExtFileBytesRecv=$True
$SmtpConfig.LogExtFileBytesSent=$True
$SmtpConfig.LogExtFileClientIp=$True
$SmtpConfig.LogExtFileComputerName=$True
$SmtpConfig.LogExtFileCookie=$false
$SmtpConfig.LogExtFileDate=$True
$SmtpConfig.LogExtFileFlags=1110127
$SmtpConfig.LogExtFileHost=$True
$SmtpConfig.LogExtFileHttpStatus=$False
$SmtpConfig.LogExtFileHttpSubStatus=$False
$SmtpConfig.LogExtFileMethod=$False
$SmtpConfig.LogExtFileProtocolVersion=$False
$SmtpConfig.LogExtFileReferer=$False
$SmtpConfig.LogExtFileServerIp=$True
$SmtpConfig.LogExtFileServerPort=$True
$SmtpConfig.LogExtFileSiteName=$False
$SmtpConfig.LogExtFileTime=$True
$SmtpConfig.LogExtFileTimeTaken=$True
$SmtpConfig.LogExtFileUriQuery=$False
$SmtpConfig.LogExtFileUriStem=$False
$SmtpConfig.LogExtFileUserAgent=$False
$SmtpConfig.LogExtFileUserName =$True
$SmtpConfig.LogExtFileWin32Status=$False
$SmtpConfig.LogFileDirectory="C:\Windows\System32\LogFiles"
$SmtpConfig.LogFilePeriod=1
$SmtpConfig.LogFileTruncateSize=19922944
$SmtpConfig.LogType=1
$null = $SmtpConfig.put()

# Test SMTP Setting
$SMTPCurrentConfig = Get-WMIObject IISSMTPServerSetting -Namespace root/MicrosoftIISv2
$smtpServer = "localhost"
$smtpPort = 25
$emailFrom = $SMTPCurrentConfig.PSComputerName+"@mydomain.com"
$emailTo = "it@mydomain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Port = $smtpPort
$subject = "Test SMTP " + $SMTPCurrentConfig.DefaultDomain
$Body = $SMTPCurrentConfig.PSComputerName
$smtp.Send($emailFrom, $emailTo, $subject, $body)

Configure Smtp Virual Server in windows Server using Powershell-(Relay,Connection)

$
0
0

Using powershell I have to enable SMTP and

  • Add relay Ip
  • Add connection IPs
  • Set Access Control Authentication

I found following code for the above operation

$GetSMTP = Get-CimInstance -Namespace "root\MicrosoftIISv2" -Class "IISSMTPServerSetting" -Filter "Name ='SmtpSvc/1'" $RelayIps = @(10,92,32,83,127,0,0,1) $GetSMTP.RelayIpList = $RelayIps Set-CimInstance -InputObject $GetSMTP $GetSMTP $GetSMTP = Get-CimInstance -Namespace "root\MicrosoftIISv2" -Class "IIsIPSecuritySetting" -Filter "Name ='SmtpSvc/1'" $NewConnectionIps = @( "10.92.32.80, 10.92.32.81";"10.92.32.83,127.0.0.1"; ) $GetSMTP.ipgrant += $NewConnectionIps Set-CimInstance -InputObject $GetSMTP $GetSMTP

The above powershell code executed successfully and it list as it is added.

while click smtp vitrual server properties, the following issue is throwing

Powershell - use of Generics with Constraints

$
0
0

Hi All, Please may i have your help with translating code from c# to powershell. The code in question uses the openxml sdk and reads an excel file which has both numeric and string data types in the cells.

The C# example code is as follows with the powershell script below. The issue I have is in Powershell I cannot see some of the methods. For example ElementAt or FirstOtDefault. I've highlighted below with ???????? where I'm expecting to see ElementAt. I think the issue is how I'm using generics with constraints in powershell, I might be wrong? Any help would be greatly appreciated

// Retrieve the value of a cell, given a file name, sheet name, // and address name.publicstaticstringGetCellValue(string fileName,string sheetName,string addressName){string value =null;// Open the spreadsheet document for read-only access.using(SpreadsheetDocument document =SpreadsheetDocument.Open(fileName,false)){// Retrieve a reference to the workbook part.WorkbookPart wbPart = document.WorkbookPart;// Find the sheet with the supplied name, and then use that // Sheet object to retrieve a reference to the first worksheet.Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name== sheetName).FirstOrDefault();// Throw an exception if there is no sheet.if(theSheet ==null){thrownewArgumentException("sheetName");}// Retrieve a reference to the worksheet part.WorksheetPart wsPart =(WorksheetPart)(wbPart.GetPartById(theSheet.Id));// Use its Worksheet property to get a reference to the cell // whose address matches the address you supplied.Cell theCell = wsPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference== addressName).FirstOrDefault();// If the cell does not exist, return an empty string.if(theCell !=null){
            value = theCell.InnerText;// If the cell represents an integer number, you are done. // For dates, this code returns the serialized value that // represents the date. The code handles strings and // Booleans individually. For shared strings, the code // looks up the corresponding value in the shared string // table. For Booleans, the code converts the value into // the words TRUE or FALSE.if(theCell.DataType!=null){switch(theCell.DataType.Value){caseCellValues.SharedString:// For shared strings, look up the value in the// shared strings table.var stringTable =
                            wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();// If the shared string table is missing, something // is wrong. Return the index that is in// the cell. Otherwise, look up the correct text in // the table.if(stringTable !=null){
                            value =
                                stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;}break;caseCellValues.Boolean:switch(value){case"0":
                                value ="FALSE";break;default:
                                value ="TRUE";break;}break;}}}}return value;}

With my attempt powershell code (not exactly the same) as follows

cls
[Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml")
[Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Packaging")
[Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Spreadsheet")
[Reflection.Assembly]::LoadWithPartialName("OpenXmlPowerTools")

Import-Module "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\GenericMethods\GenericMethods.psm1" -ErrorAction Stop

[DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]$Document = $null
$Document = [DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]::Open("C:\temp\Book1.xlsx", $false)
[DocumentFormat.OpenXml.Packaging.WorkbookPart]$WorkBookPart = $Document.WorkbookPart

[DocumentFormat.OpenXml.Spreadsheet.Workbook]$WorkBook = $WorkBookPart.Workbook
[DocumentFormat.OpenXml.Spreadsheet.Sheets]$Sheets = $WorkBook.Sheets

[DocumentFormat.OpenXml.Spreadsheet.Sheet]$Sheet = $null

foreach ($Sheet in $Sheets)
{
[DocumentFormat.OpenXml.Packaging.WorksheetPart]$WorkSheetPart = $WorkBookPart.GetPartById($Sheet.Id)

$Cells = Invoke-GenericMethod -InputObject $WorkSheetPart.Worksheet -MethodName Descendants -GenericType DocumentFormat.OpenXml.Spreadsheet.Cell
foreach ($Cell in $Cells)
{

switch($Cell.DataType.Value)
{
{$_ -eq "SharedString"}
{
Write-Host "String"
$StringTable = Invoke-GenericMethod -InputObject $WorkBookPart -MethodName GetPartsOfType -GenericType DocumentFormat.OpenXml.Packaging.SharedStringTablePart
If ($StringTable -ne $null)
{
Write-Host $StringTable.SharedStringTable.?????????
}
}
{$_ -eq "Boolean"}{Write-Host "Boolean"}
}

Write-Host $Cell.InnerText
[String]$Value = $Cell.InnerText

[DocumentFormat.OpenXml.Packaging.SharedStringTablePart]$SharedTablePart = $null

}
}
$Document.Close()

XCOM Transmition - Monitor transmition

$
0
0

Hey guys! I been trying to create a script file to monitor a directory that recieve incoming transmitions from a XCOM server. I found a FW (Filewatcher) code in internet and started from that. The thing is that i want the script to look for the creation of files and after a file a created i want to read the xcom.log until the transmition end. Every time that a transmition end there are two lines that say something like 

2015/04/06 12:38:10 TID=000062
    XCOMN0011I Transfer ended; 7913 records (561811 bytes) transmitted in 10 seconds (56181 bytes/second)

The "Transfer ended" is constant in every transmition

The script that i've created is:

$folder = 'D:\PowerShell\Files-XCOM' # Enter the root path you want to monitor.
$filter = '*.IN'  # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

# Here, all three events are registerd.  You need only subscribe to events that you need:

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = Get-Date -Format G
$VarWhile = 1
Write-Host "$timeStamp - Comienza transmision XCOM" -fore green
Out-File -FilePath D:\PowerShell\Files-XCOM\FileWatcher.log -Append -InputObject "$timeStamp - Comienza transmision XCOM"
}
While ( $VarWhile -eq 1 )
{
    $StringLog = Get-Content D:\PowerShell\Files-XCOM\xcom.log | Select-Object -Last 2
    if ( $StringLog -like '*Transfer ended*' )
    {
        $timeStamp = Get-Date -Format G
        Write-Host "$timeStamp - Transmision XCOM finalizada" -fore green
        Out-File -FilePath D:\PowerShell\Files-XCOM\FileWatcher.log -Append -InputObject "$timeStamp - Transmision XCOM finalizada"
        $VarWhile = 0
    }
}
# To stop the monitoring, run the following commands:
# Unregister-Event FileCreated 

The script detect when a file is created but i cant get to make it "enter" the while statement to read the log file

I cant find the error after several tries, any idea?

Strange result from convertto-html

$
0
0

I’m new to Powershell. I’m trying to convert the contents of a .txt file to .html

The following code displays the contents of my file without a problem

               get-content "C:\temp\FSHQ-GG-FASTsearch Developers.txt"

               AD group, SQL login

-------------------

FSHQ-GG-FASTsearch Developers,corp\acrhyme

FSHQ-GG-FASTsearch Developers,corp\amendez

FSHQ-GG-FASTsearch Developers,corp\ASedaghat-Mansouri

FSHQ-GG-FASTsearch Developers,corp\BCooper

FSHQ-GG-FASTsearch Developers,corp\cthroop

FSHQ-GG-FASTsearch Developers,corp\dpnguyen

FSHQ-GG-FASTsearch Developers,corp\MSummers

FSHQ-GG-FASTsearch Developers,corp\RDOwens

FSHQ-GG-FASTsearch Developers,corp\RVenkataramappa

FSHQ-GG-FASTsearch Developers,corp\WYan

But when I pipe it to convertto-html I get information about the file in .html format, not the file’s contents

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>HTML TABLE</title>

</head><body>

<table>

<colgroup><col/><col/><col/><col/><col/><col/><col/></colgroup>

<tr><th>PSPath</th><th>PSParentPath</th><th>PSChildName</th><th>PSDrive</th><th>PSProvider</th><th>ReadCount</th><th>Le

ngth</th></tr>

<tr><td>C:\temp\FSHQ-GG-FASTsearch Developers.txt</td><td>C:\temp</td><td>FSHQ-GG-FASTsearch Developers.txt</td><td>C</

td><td>Microsoft.PowerShell.Core\FileSystem</td><td>1</td><td>0</td></tr>

<tr><td>C:\temp\FSHQ-GG-FASTsearch Developers.txt</td><td>C:\temp</td><td>FSHQ-GG-FASTsearch Developers.txt</td><td>C</

td><td>Microsoft.PowerShell.Core\FileSystem</td><td>2</td><td>119</td></tr>

<tr><td>C:\temp\FSHQ-GG-FASTsearch Developers.txt</td><td>C:\temp</td><td>FSHQ-GG-FASTsearch Developers.txt</td><td>C</

td><td>Microsoft.PowerShell.Core\FileSystem</td><td>3</td><td>119</td></tr>

I’ve obviously missed something


Getting the Error 'The Given Key was not present in the dictionary' while running AD module PowerShell

$
0
0

Hi All,

I am trying to run the below command post importing the AD module, unfortunately I am stuck with the below error.

'The Given Key was not present in the dictionary' - Can anybody please help out here, also below is the snapshot for the same.

Regards,
Abdul Malik




SharePoint 2013 - Get hit count for a month using GetHitCountForMonth method of GetRollupAnalyticsItemData - cannot pass the month as argument

$
0
0

Hi,

I was trying to extract the hit count for a particular site collection in SharePoint 2013 using PowerShell.

While I can get the total hit count from the GetRollupAnalyticsItemData object, I cannot find a way to pass the month as parameter to the GetHitCountForMonth method. 

My code as below:

Add-PsSnapin Microsoft.SharePoint.PowerShell
$SiteColl = Get-SPSite http://mysitecollection
$SearchApp = Get-SPEnterpriseSearchServiceApplication
$UsageData = $SearchApp.GetRollupAnalyticsItemData(1,[System.Guid]::Empty,$SiteColl.ID,[System.Guid]::Empty)
[Datetime]$date = (Get-Date "2015-01-18")
$UsageData.GetHitCountForMonth($date)


I get the output:

You cannot call a method on a null-valued expression.
At line:6 char:1
+ $UsageData.GetHitCountForMonth($date)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Please help. Thanks! 

Powershell and Itextsharp - Signing a signature field

$
0
0

Well the title explains what I want to do, I found plenty of resources online to fill in any part of a form in a PDF and save it as a new pdf using powershell with the itextsharp dll loaded - even got that to work with no issues; However, I can not  find any documentation on how POWERSHELL (not C#) can sign a PDF document. 

Please do not use links to answer this question. I have all of the documentation of how to do this in C# from the itextsharp home page. 

Has any one done this in powershell? I cant find any examples online on how to Sign a signature field using .cer or any other format of a cert.

Pre Thanks!



Can someone explain why my empty param just screws me over

$
0
0

I'm scratching my head over here getting no coherence whatsoever and I guess I'm doing something wrong.

Example script:

param(
    [parameter(Mandatory=$true)] [string]$param1,
    [parameter(Mandatory=$true)] [string]$param2,
    [parameter(Mandatory=$true)] [string]$param3,
    [parameter(Mandatory=$true)] [string]$param4,
    [parameter(Mandatory=$true)] [string]$param5,
    [parameter()] [string]$param6,
    [parameter()] [string]$param7,
    [parameter()] [AllowEmptyString()] [string]$param8="",
    [parameter()] [string]$param9
     )

Write-Host "p1: $param1"
Write-Host "p2: $param4"
Write-Host "p3: $param3"
Write-Host "p4: $param4"
Write-Host "p5: $param5"
Write-Host "p6: $param6"
Write-Host "p7: $param7"
Write-Host "p8: $param8"
Write-Host "p9: $param9"

If I run this like so:

PS C:\> ./test.ps1 "1" "2" "3" "4" "5" "6" "7" "" "9"

I get a great and dandy output:

p1: 1
p2: 4
p3: 3
p4: 4
p5: 5
p6: 6
p7: 7
p8: 
p9: 9

But then if I go and run it with:

PS C:\> C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -ExecutionPolicy ByPass -File /test.ps1 "1" "2" "3" "4" "5" "6" "7" "" "9"

I get this:

p1: 1
p2: 4
p3: 3
p4: 4
p5: 5
p6: 6
p7: 7
p8: 9
p9: 

There's something I'm not getting.

PS V. 2.0

Question about Function nested twice in Workflow

$
0
0

Hello, Dear Colleagues.

Help me to deal with Function nested in Workflow, please.

Here is script layout:

function enQueue { #do something important } function deQueue { isEmpty #call Function "isEmpty" #do something important } function isEmpty { #do something important } function frontQueque { isEmpty #call Function "isEmpty" #do something important }

#$variable = "Foo" #error workflow wf { $variable = "Foo" while ($true) { sequence { isEmpty #call Function "isEmpty" - successful #do something important frontQueque #call Function "frontQueue" - error (see below) #do something important deQueue #call Function "deQueue" - error (see below) #do something important enQueue #call Function "enQueue" - successful #do something important } } } wf

Questions:

1). As you can see Functions "enQueue" and "isEmpty" is called from Workflow "wf" and executes successfully.

Function "isEmpty" is called from "frontQueque" and "deQueue" Functions, which called from Workflow "wf" and i'm getting error:  

The term 'isEmpty' 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, veri
fy that the path is correct and try again.+ CategoryInfo          : ObjectNotFound: (isEmpty:String) [deQueue], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException,deQueue+ PSComputerName        : [localhost]

How to make it work?

2). If declare Variable "$variable" outside Workflow wf,  Variable is not visible inside one. Can I deal with that?

If you need, can provide you with full script.

Thanks.





mkdir -? - - - > how is the [ -path ] option used ?

$
0
0

Would anyone be able to give an example of how the  [  -path  ]   option is used   ?    I found it when looking up more information under the ' making a directory '   command    mkdir -?

Hope this is not too vague of a  question.

Thank you in advance  !

alvino6

Unable to change keyboard layout for all users on Windows Server 2012 R2

$
0
0

Hi,

I have a requirement where I need to support national keyboard layout for Danish for all users on that machine. When I ran the powershell with script Set-WinUserLanguageList -LanguageList da-DK it only sets the Danish keyboard layout to the specific logged in user.However the for other users its same English(US) keyboard which is not expected.

Please help me how to set the Danish keyboard for all users on the machine. Its Urgent!Thanks


Using Windows Update Module remotely

$
0
0

I've downloaded and installed the Windows Update modules for powershell. The commands work perfectly locally but fails to  work remotely.  I am able to run other commands remotely such as Get-Culture.

Windows Update Module:

https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc

Example Code:

Invoke-Command -ComputerName test_server -Credential domain\me -ScriptBlock {Get-WUHistory}

Output:

The term 'Get-WUHistory' is not recognized as the name of a cmdlet, function, script file, or operable program.


Flat nested AD groups

$
0
0


Hi,

I try to create a PS script that makes nested AD groups flat. It should add all users from every nested groups in the group at first level (we want to flat).

For example:

Actual situation
Group1
	User A
	User B
	Group2
		User C
		Group3
			User D

What we need
Group1
	User A
	User B
	Group2
		User C
		Group3
			User D
	User C
	User D

Output in Logfile
Member			from group			in group
User C			Group2				Group1
User D			Group3				Group1

First I tried it with the Get-ADGroupMember cmdlet and the -recursive switch.

$Groups2Flat = Get-ADGroup -Filter {Name -like "zz8MAN*" -and Name -notlike "*_li"}
foreach ($Group2Flat in $Groups2Flat)
    {
        $Members = Get-ADGroupMember -Identity $Group2Flat -Recursive
        Add-ADGroupMember -Identity $Group2Flat -Members $Members
        Clear-Variable -Name Members
    }

This version works fine. So I wanted to add an output in a logfile. I need the following informations: which member, from which group, is added in which group. But there’s the problem. If I use the Get-ADGroupMember with the –recursive switch I can’t get these informations. I can’t see from which nested group the member comes.

So I decide to create an own recursive function. That’s what I’ve got so far:

function Flat-ADGroups {
    param (
        $Group
    )
    $Members = Get-ADGroupMember -Identity $Group
    foreach ($Member in $Members) {
        if ($Member.objectClass -eq "group") {
            Flat-ADGroups -Group $Member.Name
        }
        else {
            Add-ADGroupMember -Identity $Group -Members $Member
        }
        Clear-Variable Member
    }
}

Flat-ADGroups -Group Test_1

This code works well, too. But there is still a little problem where I don’t know what to do. The nested users weren’t add in the group at first level (of course, the function calls itself with a new groupname). They are added to the nested group. I tried a few things (second variable and so on) but nothing worked.

What is to do that the script adds all nested members to the first group? I hope I could explain the problem sufficiently.

Btw: As you can see there is no logging part at the moment and it would be useful if I include a part which deletes the nested groups after they are flatted. This things I will add later to the script. Now I only want to know what is to do to resolve my actual problem. I’m not looking for someone who writes the whole script for me ;-)

Thanks for the answers and ideas J

Need help in executing PS script (UNC Path) from a remote Azure VM

$
0
0

Hi All,

Need your help ,

I have a PS Script (in UNC path) to take a Db backup in Azure VM2 . Now I need to Invoke the PS script fromAzure VM1. 

(It works fine when I execute locally)

 When I execute like this Invoke-Expression -Command \\RemoteServer\SQLBackup\Backup1.ps1  after setting 

Get_executionpolicy // which is Unrestricted

Set-Execution policy bypass // I have set to bypass

I get an error like below :

Error : You cannot call a method on a null-valued expression.
At \\RemoteServer\SQLBackup\Backup1.ps1:17 char:5
+ if ($assemblyInfo.GetName().Version.Major -ge 10)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

new-object : Cannot find type [Microsoft.SqlServer.Management.Smo.Server]: make sure the assembly containing this type is loaded.
At \\RemoteServer\SQLBackup\Backup1.ps1:29 char:10
+     $s = new-object (“Microsoft.SqlServer.Management.Smo.Server”) $DatabaseServe ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

My PS Script looks like this : 

$BackupPath = "d:\SQLBackup"
$ServerName = "RemoteServer"
$DatabaseServer = "RemoteServer"
$DatabaseName = "XXXXXX"

# little helper function to ping the remote server.
function Get-ServerOnline ([string] $server)
{
    $serverStatus = (new-object System.Net.NetworkInformation.Ping).Send($server).Status -eq "Success"
    $dt = get-date -format yyyyMMddHHmmss
    Write-Host "$dt - Server Online: $serverStatus"
    return $serverStatus
}

# Load the SQL Server SMO Libraries
$assemblyInfo = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
if ($assemblyInfo.GetName().Version.Major -ge 10)
{
    # sql server version is 2008 or later, also load these other assemblies
    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SQLWMIManagement') | Out-Null
}

$dt = get-date -format yyyyMMddHHmmss
Write-Host "$dt - Connecting to Database Server $ServerName"

if (get-serveronline($ServerName))
{
    $s = new-object (“Microsoft.SqlServer.Management.Smo.Server”) $DatabaseServer




            if (!(Test-Path -path $BackupPath\$DatabaseName\))
            {
                $dt = get-date -format yyyyMMddHHmmss
                Write-Host "$dt - Creating the Backup Directory for $DatabaseName"
                New-Item $BackupPath\$DatabaseName\ -type directory | Out-Null
            }

            $dt = get-date -format yyyyMMddHHmmss
            Write-Host "$dt - Starting the Backup of the Database $DatabaseName"

            $dt = get-date -format yyyyMMddHHmm # We use this to make a file name based on the timestamp
            $dbBackup = new-object (“Microsoft.SqlServer.Management.Smo.Backup”)
            $dbBackup.Action = “Database”
            $dbBackup.Database = $DatabaseName
            $dbBackup.Devices.AddDevice($BackupPath +"\" + $DatabaseName + “\” + $DatabaseName + “_Database_” + $dt + “.bak”, “File”)
            $dbBackup.SqlBackup($s)

    $dt = get-date -format yyyyMMddHHmmss
    Write-Host "$dt - Database Backup Complete"
}


Abraham Dhanyaraj

Get-WmiObject

$
0
0

Hi!

Is it possible to run Get-WmiObjet simultaneously on one computer?

//Patric

Inline C# - Assembly Reference

$
0
0

Hi

I've written the C# code below to write basic website information to a text file which will then be imported via SSIS into a database.

Running this in Powershell generates the following error...

New-Object : Cannot find type [Microsoft.Web.Administration]: make sure the assembly containing this type is loaded.

Can anyone tell me where I'm going wrong here? 

Thanks!

$Assem = ("Microsoft.Web.Administration, Version 7.0.0.0, Culture=neutral","Microsoft.Web.Management, Version 7.0.0.0, Culture=neutral"
)

$Source = @"
using System;
using System.Web;
using Microsoft.Web.Administration;
using System.IO;


namespace SiteReporting
{
class Program
{
static void Main(string[] args)
{
String hostName = Environment.MachineName;
//Remove the report file previously generated
System.IO.File.Delete("c:\\windows\\temp\reportFile_" + hostName + ".csv");
//Create new text file object ready for writing later
StreamWriter reportFile = new StreamWriter("c:\\windows\\temp\reportFile_" + hostName + ".csv", true);
//Create new server manager object to expose IIS objects
ServerManager serverManager = new ServerManager();
foreach (Site vHost in serverManager.Sites)
{
foreach (Binding vHostBinding in vHost.Bindings)
{
//If vhost name is Default Web Site or Default FTP Site, do nothing and enter else statement
if (vHost.Name == "Default Web Site" || vHost.Name == "Default FTP Site")
{

}
else
{
string hostPath = vHost.Applications["/"].VirtualDirectories["/"].PhysicalPath;
//Line above returns the path to the start page. The following lines remove the filename leaving only the dir name
int lastSlash = hostPath.LastIndexOf("\\");
string dirName = hostPath.Remove(lastSlash);
DirectoryInfo di = new DirectoryInfo(dirName);
decimal dirSize = di.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length) / 1000000    ;
//Write comma separated values to text file
reportFile.WriteLine(hostName + "," + vHost.Name + "," + vHostBinding.EndPoint.Address.ToString() + "," + dirSize.ToString());
}
}

}
reportFile.Close();
}


}
}
"@

Add-Type -TypeDefinition $Source -Language CSharp


                                
Viewing all 21975 articles
Browse latest View live


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