i have a problem that is troubling my mind.
I want to automatically execute powershell scripts with named arguments but within another powershell script (that will act as a script deamon).
For example:
One of the scripts that get called has this parameters
param(
[int]$version,
[string]$user,
[string]$pass,
[string]$domain,
)
The powershell script deamon now loads the file and arguments like this
$argumentsFromScript = [System.IO.File]::ReadAllText("C:\params.txt") $job = Start-Job { & "ps1file" $arguments}
The params.txt contains the data like this
-versionInfo 2012 -user admin -pass admin -domain Workgrup
But when i try to execute this code obviously the whole $argumentsFromScript variable will be seen as parameter 1 (version) and i end up with an error, that "-versionInfo 2012 -user admin -pass admin -domain Workgrup" cannot be converted to Int32...
Do you guys have any idea how i can accomplish this task?
The Powershell deamon does not know anything about the parameters. He just needs to execute scripts with given named parameters. The params.txt is just an example. Any other file (csv,ps1,xml,etc) would be fine, i just want to automatically get the named parameters passed to the script.
Thank you in advance for any help or advice..
Try this:
#'
param ([string]$logname,[int]$newest)
get-eventlog -LogName $logname -Newest $newest
'# | sc c:\testfiles\testscript.ps1
'-logname:application -newest:10' | sc c:\testfiles\params.txt
$script = 'c:\testfiles\testscript.ps1'
$arguments = 'c:\testfiles\params.txt'
$sb = [scriptblock]::Create("$script $(get-content $argumentlist)")
Start-Job -ScriptBlock $sb
I guess you want this:
$ps1 = (Resolve-Path .\YourScript.ps1).ProviderPath
$parms = (Resolve-Path .\YourNamedParameters.txt).ProviderPath
$job = sajb -ScriptBlock {
param($ps1,$parms)
iex "$ps1 $parms"
} -ArgumentList #(
$ps1,
[string](gc $parms)
)
# if you wanna see the outcome
rcjb $job -Wait
Related
On SQL Server 2016 I have setup a job that executes a powershell script that resides on a remote app server. When I execute the powershell script via the app server using the Powershell ISE app my script works without issue. When I had setup the job and enter this command:
powershell.exe -ExecutionPolicy Bypass -file "\\serverapp1\c$\coverageverifier_scripts\SFTP_CoverageVerifier.ps1" in Step 1.
When I look at the VIEW HISTORY I see the error below but I cannot figure out why the script now cannot load the file or assembly.
Any help/direction would be appreciated. Here is the error:
The job script encountered the following errors. These errors did not stop the script: A job step received an error at line 1 in a PowerShell script. The corresponding line is 'powershell.exe -ExecutionPolicy Bypass -File "\empqaapp1\c$\coverageverifier_scripts\SFTP_CoverageVerifier.ps1"'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Add-Type : Could not load file or assembly '
Here is my powershell script as well:
# Load WinSCP .NET assembly
#Add-Type -Path "WinSCPnet.dll"
Add-Type -Path (Join-Path $PSScriptRoot "WinSCPnet.dll")
# Declare variables
$date = Get-Date
$dateStr = $date.ToString("yyyyMMdd")
# Define $filePath
$filePath = "C:\coverageverifier_scripts\TEST_cvgver.20190121.0101"
# Write-Output $filePath
# Set up session options for VERISK TEST/ACCEPTANCE SFTP SERVER
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "secureftpa.iso.com"
UserName = "account"
Password = "pw"
SshHostKeyFingerprint = "ssh-rsa 1111 xxx/xxxxxxxxx+3wuWNIkMY5GGgRObJisCPM9c9l7yw="
}
$session = New-Object WinSCP.Session
$session.ExecutablePath = "C:\WinSCP\WinSCP.exe"
try
{
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.PutFiles($filePath,"/").Check()
}
finally
{
$session.Dispose()
Your Add-Type call does not include the path to the WinSCPnet.dll.
If you have the WinSCPnet.dll in the same folder as your PowerShell script, use this syntax:
Add-Type -Path (Join-Path $PSScriptRoot "WinSCPnet.dll")
Or use a full path.
See also Loading assembly section in WinSCP .NET assembly article on Using WinSCP .NET Assembly from PowerShell.
I'm trying to write a script in Power Shell to connect to a remote server and execute a .bat file. Since I wanted to do this for more than one server I thought I could place the .bat file on another server which shares ist resources and call it from there, but that does not work. When I place the .bat file in my temp folder and execute it via the script it works. However trying to execute it from the shared resources does not. Why is that?
Note: I can manually start the process via the Task-Manager that starts the .bat file in the shared resources and it works.
script:
$CompName = "myotherserver"
$cred = get-credential
$process = get-wmiobject -query "SELECT * FROM Meta_Class WHERE __Class = 'Win32_Process'" -namespace "root\cimv2" -computername $CompName -credential $cred
$results = $process.Create( "cmd.exe `/c \\mysharedresc\temp\started.bat" )
started.bat:
echo started > c:\temp\started.txt
If you need more annotations or Information please ask for it.
Edit: Working means for me it creates the started.txt in C:\temp. Not working means it does not (but in this case there is no error given.)
please help. I have a the following function.
PROCESS {
$ServersArray = #('localhost')
foreach ($serverArray in $ServersArray) {
try {
if ($WebConfig.SelectedIndex -gt -1) {
Write-Host -ForegroundColor Cyan "Applying Maintenance on $ServerArray"
$everything_ok = $true
Invoke-Command $serverArray -ScriptBlock {
$filePath = "D:\\Inetpub\\MyHL3Ordering\\Configuration\\MyHL" + "\\" + $WebConfig.SelectedItem
(Get-Content $filePath) | ForEach-Object {
$_ -replace 'allowDO="true"','allowDO="false"'
} | Set-Content $filePath -Encoding UTF8;
} -ErrorAction 'Stop'
}
so basically I would like to concatenate the path with the combobox selected item. for example. if the selected item is web_da-DK.config , the path should be
'D:\Inetpub\MyHL3Ordering\Configuration\MyHL\web_da-DK.config' but it is not working.
error is:
Cannot find part of the path 'D:\Inetpub\MyHL3Ordering\Configuration\MyHL\' it doesnt seem to concatenate the value of combobox selectedItem to the path.
Please let me know what am I doing wrong.
The problem is that you are trying to use a variable from a scope in which is does not exist. You can read more about scopes if you run the following command:
Get-Help about_scopes
Since you are using PowerShell v3 you can use the Using scope modifier. From the help on about_scopes:
The Using scope modifier
Using is a special scope modifier that identifies a local
variable in a remote command. By default, variables in remote
commands are assumed to be defined in the remote session.
The Using scope modifier is introduced in Windows PowerShell 3.0.
For more information, see about_Remote_Variables.
It further suggest reading the about_Remote_Variables, which states:
USING LOCAL VARIABLES
You can also use local variables in remote commands, but you must
indicate that the variable is defined in the local session.
Beginning in Windows PowerShell 3.0, you can use the Using scope
modifier to identify a local variable in a remote command.
The syntax of Using is as follows:
The syntax is:
$Using:<VariableName>
In order to take an example of this, we could make a sample first which tries to use the local variable immediately, like the following:
$serverArray = "localhost"
$filename = "somefile.txt"
Invoke-Command -ComputerName $ServerArray -ScriptBlock {
$concatenated = [System.IO.Path]::Combine("C:\rootpath", $filename)
Write-Host $concatenated
}
This will yield the following output:
C:\rootpath
If we change the script to use the Using scope modifier to indicate that we want to use a local variable from the remote scope, we get code like the following:
$serverArray = "localhost"
$filename = "somefile.txt"
Invoke-Command -ComputerName $ServerArray -ScriptBlock {
$concatenated = [System.IO.Path]::Combine("C:\rootpath", $Using:filename)
Write-Host $concatenated
}
This will yield the output which we want, that is:
C:\rootpath\somefile.txt
So what you need to do is to either pass it as an argument to the Invoke-Command function, using the -ArgumentList parameter, or (since you are using PowerShell v3) indicate that your variable is a local variable and use the Using scope modifier like the examples above.
I am looking to set "password never expires" for a local Windows user account, for a list of servers in a text file. So far, I found this command line below, but it only works local on single computer. How can I incorporate this into a VBscript, PowerShell, or batch file to apply on a list of servers in a text file?
WMIC USERACCOUNT WHERE "Name='accountname'" SET PasswordExpires=FALSE
This code should do it:
# 1. Define in-line array of servers
$ServerList = #('localhost', 'localhost', 'localhost');
# 2. Define account name
$AccountName = 'test';
# 3. For each server, set the account to expire
foreach ($Server in $ServerList) {
$Account = Get-WmiObject -ComputerName $Server -Class Win32_UserAccount -Filter "Name = '$AccountName'";
$Account.PasswordExpires = $false;
[void] $Account.Put();
}
If you want to import a text file that contains the server names, you can simply change the first line to this:
$ServerList = Get-Content -Path c:\path\to\text\file.txt;
An alternative method would be to use Invoke-Command, however this requires that you first configure PowerShell Remoting in your environment.
# 1. Define in-line array of servers
$ServerList = #('localhost', 'localhost', 'localhost');
# 2. Define the block of code to deploy (a PowerShell ScriptBlock)
$ScriptBlock = {
$AccountName = 'test';
$Account = Get-WmiObject -Class Win32_UserAccount -Filter "Name = '$AccountName'";
$Account.PasswordExpires = $false;
[void] $Account.Put();
};
# 3. Deploy the ScriptBlock to the array of servers
Invoke-Command -ComputerName $ServerList -ScriptBlock $ScriptBlock;
To configure PowerShell Remoting, run the Enable-PSRemoting -Force command on each computer. You can also use Active Directory Group Policy to enable PowerShell Remoting / Windows Remote Management (WinRM).
wmic can be run against remote hosts via the /node parameter:
wmic /node:HostA,HostB useraccount where "Name='accountname'" ...
I've created a PowerShell script that runs perfectly from the Management Shell. I'm trying to get it setup to work in a scheduled task in Windows Server 2008 R2 and am unsure how to pass the parameters for my string array parameter.
Here is the relevant portion of my script:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]
$BaseDirectory,
[String]
$BackupMethod = "Full",
[Int]
$RemoveOlderThanDays = 0,
[String]
$LogDirectory,
[Int]
$LogKeepDays = 7,
[String[]]
$AdditionalDirectories
)
if ($AdditionalDirectories -and $AdditionalDirectories.Count -gt 0) {
Write-Host " Additional Directories to be included:" -ForegroundColor Green
$AdditionalDirectories | ForEach-Object {
Write-Host " $_" -foregroundcolor green
}
}
The parameter giving the trouble is that last one, $AdditionalDirectories.
From the Shell:
If I run the script from the Management Shell like this, it works perfectly:
.\FarmBackup.ps1 \\SomeServer\Backups Full 0 D:\Logs\Backups 0 "D:\Documents\PowerShell Scripts","D:\SomeFolder"
Result:
Additional Directories to be included:
D:/Documents/PowerShell Scripts
D:/SomeFolder
From Scheduled Task:
Action: Start a program
Program/script: PowerShell.exe
Arguments: -File "D:\Documents\PowerShell Scripts\FarmBackup.ps1" \\SomeServer\Backups Full 0 D:\Logs\Backups 0 "D:\Documents\PowerShell Scripts","D:\SomeFolder"
Result: (From Log File)
Additional Directories to be included:
D:\Documents\PowerShell Scripts,D:\SomeFolder
I've tried a couple of different methods for those parameters but I can't seem to get them to be seen as 2 separate strings in the string array. I'm hardcoding them for now, but it seems like there must be a way to make this work since it's totally valid when run from the shell.
Try using the -Command switch instead of the -File switch, and then use the invocation operator '&'. Here is a link to an example of doing this with scheduled tasks:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/schedule-powershell-scripts-that-require-input-values.aspx
Something like:
-Command "& 'D:\Documents\PowerShell Scripts\FarmBackup.ps1' '\\SomeServer\Backups' 'Full' 0 'D:\Logs\Backups' 0 'D:\Documents\PowerShell Scripts','D:\SomeFolder'"
I tested this solution by creating a script with the contents:
param([string[]] $x)
Write-Host $x.Count
Then called it in the following two ways:
powershell -File ".\TestScript.ps1" "what1,what2"
with result : 1
and
powershell -Command "& .\TestScript.ps1 what1,what2"
with result: 2
Another option, when the options get too complex and you're tired of fiddling with quotes, backticks, etc is to use the underused -EncodedCommand parameter on PowerShell.exe e.g.:
C:\PS> $cmd = "c:\temp\foo.ps1 'D:\Documents\PowerShell Scripts','D:\SomeFolder'"
C:\PS> $cmd
c:\temp\foo.ps1 'D:\Documents\PowerShell Scripts','D:\SomeFolder'
C:\PS> $bytes = [Text.Encoding]::Unicode.GetBytes($cmd)
C:\PS> $encodedCmd = [Convert]::ToBase64String($bytes)
C:\PS> $encodedCmd
YwA6AFwAdABlAG0AcABcAGYAbwBvAC4AcABzADEAIAAnAEQAOgBcAEQAbwBjAHUAbQBlAG4AdABzAFwAUABvAHcAZQByAFMAaABlAGwAbAAgAFMAYwByAGkAcAB0AHMAJwAsACcARAA6AFwAUwBvAG0AZQBGAG8AbABkAGUAcgAnAA==
C:\PS> powershell.exe -encodedCommand YwA6AFwAdABlAG0AcABcAGYAbwBvAC4AcABzADEAIAAnAEQAOgBcAEQAbwBjAHUAbQBlAG4AdABzAFwAUABvAHcAZQByAFMAaABlAGwAbAAgAFMAYwByAGkAcAB0AHMAJwAsACcARAA6AFwAUwBvAG0AZQBGAG8AbABkAGUAcgAnAA==
param1[0] is D:\Documents\PowerShell Scripts
param1[1] is D:\SomeFolder
Admittedly, not something that would be exactly readable/understandable by someone else. :-) You'd have to doc the command in the description of the scheduled task.
I have been using PowerShell for SharePoint and have created several Scheduled Task to trigger them at various intervals.
This is how i do it and it worked for me all the time.
Syntax : [Path to ur script'] -Param1Name 'Value1' -Param2Name 'Value2' -Param3Name 'Value3'
Here is a real example :
D:\Scripts\Global.ps1 -DataLocation 'D:\Scripts' -DeploymentParameters 'Deploymentparameters' -Deployments 'Deployments' -GlobalParameters 'GlobalParameters' -SiteUrl 'https://my.sp.company.com'