I'm attempting to use Invoke-Command to get a list of application pools on multiple remote servers. So far I have something like:
$servers = Get-Content -Path "C:\Path\to\servers.txt"
$array = New-Object -TypeName 'System.Collections.ArrayList'
foreach ($server in $servers) {
Invoke-Command -ComputerName $server -ScriptBlock {
Import-Module WebAdministration
$sites = Get-ChildItem IIS:\sites
foreach ($site in $sites) {
$array.Add($site.bindings)}}}
However I get the error:
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : computername
I've tried using regular arrays instead of ArrayLists and I get the following error:
Method invocation failed because [Microsoft.IIs.PowerShell.Framework.ConfigurationElement] doesn't contain a method named 'op_Addition'.
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
+ PSComputerName : computername
Can anyone help point me in the right direction?
Your object $arrayis not known on your remote servers. So, one proposition is to send your array to the remote server, then add some values and return it :
$servers = Get-Content -Path "C:\Path\to\servers.txt"
$array = New-Object -TypeName 'System.Collections.ArrayList'
foreach ($server in $servers) {
$array = Invoke-Command -ComputerName $server -ScriptBlock {
param($array)
Import-Module WebAdministration
$sites = Get-ChildItem IIS:\sites
foreach ($site in $sites) {
[void]($array.Add($site.bindings))
}
$array
} -ArgumentList $array
}
Related
I am trying to backup one particular stored procedure from a SQL Server database by passing parameters from a Python program. Here is the code that I have tried but I keep getting an error.
param([string]$server='dbsed0898', [string]$dbname='global_hub',[string]$sp='dbo.gs_eligibility')
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | out-null
$SMOserver = 'Microsoft.SqlServer.Management.Smo' #-argumentlist $server
$srv = New-Object("$SMOserver.Server") $server
$db = $srv.databases[$dbname]
$Objects = $db.storedprocedures[$sp]
$scripter = new-object ("$SMOserver.Scripter") $srv
$Scripter.Script($Objects) | Out-File
" C:\Users\fthoma15\Documents\backup_03212020.sql"
$db = $SMOserver.databases[$dbname]
$Objects = $db.storedprocedures[$sp]
$Scripter.Script($Objects) | Out-File
"C:\Users\fthoma15\Documents\backup_03212020.sql"
Error:
Multiple ambiguous overloads found for "Script" and the argument count: "1".
At line:12 char:5
+ $Scripter.Script($Objects) | Out-File "C:\Users\fthoma15\Document ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Can someone help me?
Here is what i did.
param([string]$server='test', [string]$dbname='test',[string[]]$sp=('test','test'))
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | out-
null
$SMOserver = new-object ("Microsoft.SqlServer.Management.Smo.Scripter") #-argumentlist
$server
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("$server")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $srv.Databases.Item("$dbname")
$Objects = $db.storedprocedures[$sp[1,3]]
$scripter = new-object ("$SMOserver") $srv
$Scripter.Script($Objects) | Out-File
"C:\Users\fthoma15\Documents\backup_03212020.sql"
As suggested by AlwaysLearning, i changed the sp variable to an array list,splitting both schema and sp name.
I'm trying to make a script that checks how long the computers on a network are on, and if they are on for more then 10 days they need to restart. I'm planning to run the script automatically with task manager every Sunday.
Thanks to #vonPryz I've got something like this now:
$clients = get-content "C:\Documents\lijstcomputers.txt"
foreach ($client in $clients) {
if (test-connection -computername $client -BufferSize 16 -Count 1 -Quiet) {
write-Host $client is online
$uptime = (get-date) - (gcim Win32_OperatingSystem -computer $client).LastBootUpTime
$startTime = [Management.ManagementDateTimeConverter]::ToDateTime((gwmi Win32_OperatingSystem -computer $client).lastbootuptime)
if( $uptime.days -ge 10) {
restart-computer -computername $client
add-content -path "c:\path\to\log.txt" -value "$client, $startTime, $uptime"
}
}
else {
write-Host $client is offline
}
}
But now I'm getting this error:
gcim : WinRM cannot complete the operation. Verify that the specified computer name is valid, that the computer is accessible over the network, and
that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM firewall exception for publ
ic profiles limits access to remote computers within the same local subnet.
At line:1 char:25
+ $uptime = (get-date) - (gcim Win32_OperatingSystem -computer $client).LastBootUp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ConnectionError: (root\cimv2:Win32_OperatingSystem:String) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80338126,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : ASND0042
Cannot find an overload for "op_Subtraction" and the argument count: "2".
At line:1 char:1
+ $uptime = (get-date) - (gcim Win32_OperatingSystem -computer $client).LastBootUp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Since you already got some parts covered, this isn't just a plz give me teh codez and thus warrants help. So let's outline how the whole script should look.
# Write computer names into a file, one per row for easier management
$clients = get-content "c:\ListOfComputers.txt"
foreach ($client in $clients) {
# If computer's not up, there's no need to check uptime
if (test-connection -computername $client -BufferSize 16 -Count 1 -Quiet) {
write-Host $client is online
# Get uptime
$uptime = (get-date) - (gcim Win32_OperatingSystem -computer $client).LastBootUpTime
# Get start time
$startTime = [Management.ManagementDateTimeConverter]::ToDateTime((gwmi Win32_OperatingSystem -computer $client).lastbootuptime)
# Restart the client if uptime's at least 10 days.
if( $uptime.days -ge 10) {
restart-computer -computername $client
# Add client name, start date and uptime into a log file
add-content -path "c:\path\to\log.txt" -value "$client, $startTime, $uptime"
}
}
else {
write-Host $client is offline
}
}
This skeleton can be further improved by adding some error handling and, say, proper CSV export.
I have a PowerShell script which works well when I run it on server with SQL Server default instance (MSSQLSERVER) but the same script fails on a server with a named instance (MSSQL$instance)
For the default instance (MSSQLSERVER)
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$service = Get-service -name 'MSSQLSERVER'
$status = $service.status
$CreateDB = "db-Test"
if ( $status -eq "Running" )
{
'Success' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, "$CreateDB")
$db.Create()
$db.CreateDate
}
else
{
'Failed' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
}
Above script works very well. But below script throws error :
For named instance :
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$service = Get-service -name 'MSSQL$instancename'
$status = $service.status
$CreateDB = "db-Test"
if ( $status -eq "Running" )
{
'Success' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, "$CreateDB")
$db.Create()
$db.CreateDate
}
else
{
'Failed' | Out-File -FilePath c:\sqltest.log -Encoding ASCII
}
Above script for named SQL instance throws below error :
New-Object : Exception calling ".ctor" with "2" argument(s): "SetParent failed for Database 'Netmagic-Test'. "
At C:\mssql-test.ps1:11 char:7
+ $db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, "$CreateDB")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\mssql-test.ps1:12 char:1
+ $db.Create()
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Error Screen
Thanks,
Viral
After extracting a list from SharePoint, I need to validate each Item against its BRTeam value. Here is the script:
cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
$sourceWebUrl = "http://theoracle/WorkingHere/"
$sourceListName = "Policies & Procedures"
$spSourceWeb = Get-SPWeb $sourceWebUrl
$spSourceList = $spSourceWeb.Lists[$sourceListName]
$spSourceItems = $spSourceList.Items
$spSourceItems | ForEach-Object {
Write-Host $_['Name']
Write-Host $_['BRTeam']
}
The code works fine in terms of getting the data and writing the required items to the host.
However, if I add the following If-Statement to validate the items, I am seeing an error:
if ($_['BRTeam'].Contains('HR')) {
Write-Host $_['Name']
Write-Host $_['BRTeam']
}
I have also tried replacing the Boolean check with $x -contains 'HR' after assigning $x = $_['BRTeam'], but this returns no output (no error either). Error below:
Method invocation failed because [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue] doesn't contain a method named 'Contains'.
At line:21 char:9
+ if ($_['BRTeam'].Contains('HR')) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Can anyone let me know what I am missing here?
I was able to resolve this by using the -Match operator instead:
$spSourceItems | ForEach-Object {
#Write-Host $_['ID']
#Write-Host $_['Workflow Started']
$x = $_['BRTeam']
if ($_['BRTeam'] -Match 'HR') {
Write-Host $_['Name']
}
}
If I am concerned that some other BRTeams may contain HR without actually being HR, I could also perform a -NotMatch against all the other departments.
E.g.:
$spSourceItems | ForEach-Object {
#Write-Host $_['ID']
#Write-Host $_['Workflow Started']
$x = $_['BRTeam']
if ($_['BRTeam'] -Notmatch 'Accounts' -And $_['BRTeam'] -Notmatch 'IT') {
Write-Host $_['Name']
}
}
im trying to set some rights on a newly created user in AD.
After I have created the folder, I try to set the various rights like this:
$Rights = [System.Security.AccessControl.FileSystemRights]::FullControl
$Inherit = #([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
$Propagation = [System.Security.AccessControl.PropagationFlags]::None
$Access =[System.Security.AccessControl.AccessControlType]::Allow
$ACL = New-Object System.Security.Principal.NTAccount "localdomain\$userprincipalname"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($ACL, $Rights, $Inherit, $Propagation, $Access)
$ACL = Get-Acl -Path $userDir
$ACL.AddAccessRule($objACE)
Set-ACL -Path $userDir -AclObject $ACL
The error I get is related to the parameters i pass to AddAccessRule
Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
But I cannot see any error here, so I would really appreciate another set of eyes.
Ok so my solution works, and as far as I can find, is the way to set rights on a folder.
$Rights = [System.Security.AccessControl.FileSystemRights]::FullControl
$Inherit = #([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
$Propagation = [System.Security.AccessControl.PropagationFlags]::None
$Access =[System.Security.AccessControl.AccessControlType]::Allow
$ACL = New-Object System.Security.Principal.NTAccount "localdomain\$userprincipalname"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($ACL, $Rights,$Inherit, $Propagation, $Access)
$ACL = Get-Acl -Path $userDir
$ACL.AddAccessRule($objACE)
Set-ACL -Path $userDir -AclObject $ACL